Realization of Universal Domain Name Resolution in CodeIgniter

  • 2021-07-10 18:55:44
  • OfStack

Recently, I encountered a project requiring the use of level 2 domain names to facilitate SEO. Because CodeIgniter framework is adopted, although this framework provides flexible routing functions, it cannot realize level 2 domain names. After inquiring many materials, the solution was obtained after several tests. This example uses the dummy domain name www. mysite. com.

Step 1:

First, establish virtualhost in httpd. conf


<VirtualHost *:80>
  ServerAdmin admin@163.com
  DocumentRoot "D:/www/cms"
  ServerName www.mysite.com
  ServerAlias *.mysite.com # The way of universal analysis is adopted here 
  ErrorLog "logs/mysite.com-error.log"
  CustomLog "logs/mysite.com.log" common
</VirtualHost>

Step 2:

I want to achieve this effect:
http://www.mysite.com/category/news/1.html ===== > http://category.mysite.com/news/1.html
To ensure proper access to this domain, you must modify the hosts file


127.0.0.1 www.mysite.com
127.0.0.1 category.mysite.com

Step 3:

Modification: _set_uri_string method for system/core/URI. php


/**
 * Set the URI String
 *
 * @access public
 * @param string
 * @return string
 */
function _set_uri_string($str)
{
 // Filter out control characters
 $str = remove_invisible_characters($str, FALSE);
 // If the URI contains only a slash we'll kill it
 $this->uri_string = ($str == '/') ? '' : $str;
 // Add by fengyun for url rewrite at 2013-1-25 1:02:27
 @include(APPPATH.'config/domain'.EXT);
 $arrServerName = explode('.', $_SERVER['SERVER_NAME']);
 if (in_array($arrServerName[0], $domain)) {
 $this->uri_string = '/' . $arrServerName[0]."/" . $this->uri_string;
 }
}

The main purpose here is to make URL correctly understood by CI.

Step 4: Create an domain. php file under application/config/. The contents are as follows:


<?php
if ( ! defined('BASEPATH'))
exit('No direct script access allowed');
$domain = array('category',"detail","info","archive");

This is pretty much done, however, when using site_url (), if you want to use a level 2 domain name, you have to do something else.


Related articles: