You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodeIgniter 4部署AWS EC2后非首页路由失效问题求助

修复CodeIgniter 4 AWS EC2路由404问题

1. 启用Apache重写模块

登录EC2实例,执行以下命令开启URL重写模块并重启Apache:

sudo a2enmod rewrite
sudo systemctl restart apache2

2. 配置虚拟主机重写权限

打开你的域名虚拟主机配置文件(通常路径为/etc/apache2/sites-available/your-domain.conf),确保<Directory>块中设置AllowOverride All,示例配置如下:

<VirtualHost *:80>
    ServerName domain.com
    ServerAlias www.domain.com
    DocumentRoot /var/www/your-ci4-project/public

    <Directory /var/www/your-ci4-project/public>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/your-domain-error.log
    CustomLog ${APACHE_LOG_DIR}/your-domain-access.log combined
</VirtualHost>

修改完成后重启Apache生效:

sudo systemctl restart apache2

3. 验证项目根目录的.htaccess文件

确保CodeIgniter 4项目的public目录下存在正确的.htaccess文件,内容如下:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

若文件不存在,直接创建并添加上述内容,同时设置正确的权限:

sudo chown www-data:www-data /var/www/your-ci4-project/public/.htaccess
sudo chmod 644 /var/www/your-ci4-project/public/.htaccess

4. 检查CodeIgniter 4核心配置

打开app/Config/App.php文件,确认以下配置项:

  • public $baseURL 设置为你的域名,例如'https://domain.com/'
  • public $indexPage 设置为空字符串'',移除URL中的index.php后缀

5. 清理CodeIgniter缓存

若以上步骤完成后问题仍存在,清理项目缓存文件:

sudo rm -rf /var/www/your-ci4-project/writable/cache/*
sudo rm -rf /var/www/your-ci4-project/writable/session/*

内容的提问来源于stack exchange,提问作者Dev-farzan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 01:57:04