Docker化CodeIgniter应用跳转页面出现Apache 404错误求助
CodeIgniter Docker化后非首页404问题排查与解决
问题情况
- 已完成基于PHP(CodeIgniter框架)和MySQL的应用Docker化部署
- 首页
http://172.18.0.4/welcome可正常访问 - 访问其他页面(如
http://172.18.0.4/welcome/contact)时触发404错误:
Not Found The requested URL was not found on this server. Apache/2.4.38 (Debian) Server at localhost Port 80
- 该应用在XAMPP环境下所有页面运行正常,尝试修改
.htaccess和routes.php后问题未解决
已修改的配置文件
.htaccess文件
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L]
修改后的routes.php
$route['default_controller'] = 'welcome'; $route['tentang'] = 'welcome/tentang'; $route['pelajaran'] = 'welcome/pelajaran'; $route['kontak'] = 'welcome/kontak'; $route['guru'] = 'welcome/guru'; $route['admin'] = 'welcome/admin'; $route['404_override'] = ''; $route['translate_uri_dashes'] = false;
原routes.php
$route['default_controller'] = 'welcome'; $route['404_override'] = ''; $route['translate_uri_dashes'] = false;
解决步骤
1. 启用Apache Rewrite模块
Docker的Apache镜像默认未开启rewrite模块,需在Dockerfile中添加以下命令开启:
RUN a2enmod rewrite
执行后重新构建镜像并启动容器。
2. 配置Apache虚拟主机允许.htaccess生效
修改Apache虚拟主机配置(如000-default.conf),在站点目录的<Directory>块中设置允许覆盖:
<Directory /var/www/html> Options Indexes FollowSymLinks MultiViews AllowOverride All Require all granted </Directory>
如果使用Docker,可通过Dockerfile将自定义配置文件复制到容器:
COPY ./000-default.conf /etc/apache2/sites-available/000-default.conf
3. 调整.htaccess的Rewrite规则格式
部分Apache版本不兼容index.php/$1的写法,改为以下格式:
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?/$1 [QSA,L]
4. 修正CodeIgniter的base_url配置
检查application/config/config.php中的$config['base_url'],设置为容器的访问地址:
$config['base_url'] = 'http://172.18.0.4/';
也可以用动态方式避免硬编码:
$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http"); $config['base_url'] .= "://".$_SERVER['HTTP_HOST']; $config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
5. 检查容器内文件权限
确保Apache用户(www-data)拥有应用目录的读取权限,在Dockerfile中添加:
RUN chown -R www-data:www-data /var/www/html RUN chmod -R 755 /var/www/html
内容的提问来源于stack exchange,提问作者Iqbal Rizky Maulana
相关产品推荐
相关产品推荐

