我想知道是否可以在Codeigniter 3中使用htaccess覆盖routes.php规则。
例如,为了将动态子域指向相同的控制器并将子域作为参数传递,routes.php无法做到这一点,而在htaccess中则非常简单。
另一个示例是使用URL段屏蔽查询字符串。 Routes.php不允许使用查询字符串,但htaccess再次是完美的。
因此,作为一般性问题,是否可以在CodeIgniter中使用htaccess进行所有路由而不是使用routes.php?
我认为你可以在codeigniter中使用htaccess进行静态路由。但对于像http://localhost/myproject/user/1这样的动态路由应用程序库,你必须使用routes.php。
Codeigniter路由配置用于路由模块/控制器/方法/变量模式。
我认为,域/子域名从这个配置中出来,但你可以使用基于$ _SERVER变量的dinamic base_url,然后从特定的控制器获取字符串(子域)。
从我的配置,在CI 2.x上
$config['base_url'] = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ? 'https' : 'http';
$config['base_url'] .= '://'. $_SERVER['HTTP_HOST'];
$config['base_url'] .= isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != '80' && $_SERVER['SERVER_PORT'] != '443' ? ( ':'.$_SERVER['SERVER_PORT'] ) : '';
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
然后做这样的事......
$server = $_SERVER['HTTP_HOST'];
$domain = preg_replace('#^www\.(.+\.)#i', '$1', $server);
$domain = $this->extract_domain($domain);
$subdomain = $this->extract_subdomains($server);
function extract_domain($domain)
{
if(preg_match("/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i", $domain, $matches))
{
return $matches['domain'];
} else {
return $domain;
}
}
function extract_subdomains($domain)
{
$subdomains = $domain;
$domain = $this->extract_domain($subdomains);
$subdomains = rtrim(strstr($subdomains, $domain, true), '.');
return $subdomains;
}