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

CodeIgniter 4线上服务器URL路由报400 Bad Request错误求助

解决CodeIgniter 4.2.8部署后URL路由400 Bad Request问题

核心问题分析

你的问题源于两处关键配置冲突:

  • .htaccess 中www转非www的规则与App.php里的baseURL设置不一致,导致请求跳转后URL不符合框架预期
  • 路由转发的RewriteRule路径错误,指向了不存在的上级目录index.php

具体修改步骤

1. 统一域名规则与baseURL

你在App.php中设置的baseURL是http://www.example.com,但.htaccess里的规则会强制将www域名跳转到不带www的版本,这会触发框架的URL校验,导致400错误。

方案二选一:

  • 若想保留www域名,修改.htaccess的域名跳转规则为强制使用www:
# 替换原有的www转非www规则
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
  • 若想使用不带www的域名,修改exampleCI4/app/Config/App.php的baseURL为:
public $baseURL = 'http://example.com';

2. 修正路由转发路径

当前.htaccess中的转发规则指向../index.php/$1,但你的index.php就在web根目录public_html/www.example.com下,向上跳转的路径会指向错误文件,引发异常。

修改这一行:

# 原错误规则
RewriteRule ^([\s\S]*)$ ../index.php/$1 [L,NC,QSA]

# 改为以下正确路径
RewriteRule ^([\s\S]*)$ index.php/$1 [L,NC,QSA]

3. 可选:启用RewriteBase增强兼容性

取消.htaccess中RewriteBase的注释并设置为根目录,提升服务器兼容性:

RewriteBase /

4. 确认路由配置(全新项目可跳过)

检查exampleCI4/app/Config/Routes.php,确保/home路由已正确配置(全新CI4默认已包含):

$routes->get('home', 'Home::index');

修改后的完整.htaccess示例

#Disable directory browsing
Options -Indexes

# ----------------------------------------------------------------------
# Rewrite engine
# ----------------------------------------------------------------------

<IfModule mod_rewrite.c>
    Options +SymLinksIfOwnerMatch
    RewriteEngine On
    RewriteBase /

    # Redirect Trailing Slashes...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # 强制使用www域名(与baseURL保持一致)
    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

    # 转发请求到index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([\s\S]*)$ index.php/$1 [L,NC,QSA]

    # Ensure Authorization header is passed along
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

<IfModule !mod_rewrite.c>
    ErrorDocument 404 index.php
</IfModule>

# Disable server signature start
ServerSignature Off
# Disable server signature end

修改完成后,等待服务器配置生效(或重启Apache服务),此时访问www.example.com/home即可正常加载页面。

内容的提问来源于stack exchange,提问作者Ronin-0822

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:45:17