Codeigniter子目录中通配符路由失效(仅通配路由异常)
子目录环境下CodeIgniter通配符路由404问题
问题情况
- 本地环境中,通配符路由可正常访问:
http://project.localhost/izvlacenje-2022/renovate - 部署到服务器的
staging子目录后,访问同一路由出现404错误:https://our-domain/staging/izvlacenje-2022/renovate - 非通配符路由在子目录下工作正常,例如:
https://our-domain/staging/intro
当前相关配置
路由规则
通配符路由:
$route['izvlacenje-2022/(:any)']['GET'] = 'WinnersController/draw_screen/$1';
正常工作的非通配符路由示例:
$route['intro']['GET'] = 'LandingsController/index';
.htaccess 配置
DirectoryIndex index.php <IfModule mod_rewrite.c> RewriteEngine on RewriteBase /staging RewriteCond $1 !^(index\.php|resources|gallery|json|slider|robots\.txt) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L,QSA] </IfModule> <IfModule !mod_rewrite.c> ErrorDocument 404 index.php </IfModule>
CodeIgniter 核心配置
$config['index_page'] = '';
排查与解决方法
确认base_url配置正确性
检查application/config/config.php中的base_url是否设置为子目录路径:$config['base_url'] = 'https://our-domain/staging/';CodeIgniter的路由匹配基于
base_url之后的路径,若该配置错误,会导致通配符路由无法正确匹配。调整RewriteRule的参数
部分服务器环境对URL重写的路径分隔符处理存在差异,尝试修改.htaccess中的RewriteRule:RewriteRule ^(.*)$ index.php?/$1 [L,QSA]或者注释掉
RewriteBase,让Apache自动识别路径:# RewriteBase /staging检查路由规则的匹配优先级
确保通配符路由没有被其他更具体的路由规则覆盖,将该通配符路由放在路由配置文件的末尾,避免被提前匹配的规则拦截。验证mod_rewrite模块状态
通过phpinfo()页面确认服务器是否启用了mod_rewrite模块,部分共享主机可能存在模块启用异常的情况。
内容的提问来源于stack exchange,提问作者failedCoder
相关产品推荐
相关产品推荐

