Apache未启用mod_rewrite或未允许.htaccess解析导致Laravel/ThinkPHP路由404;需执行a2enmod rewrite、配置AllowOverride All并重启服务;nginx则需正确设置try_files和PHP处理器。

Apache 未启用 mod_rewrite 导致 Laravel/ThinkPHP 路由 404
直接结论:不是 PHP 本身的问题,是 Apache 的 mod_rewrite 模块没开,或 .htaccess 未被允许解析。PHP 脚本能正常执行,但所有非 index.php 的 URL 都会 404 —— 因为重写规则根本没生效。
- 检查是否加载模块:
a2enmod rewrite
(Debian/Ubuntu);若提示已启用,再确认/etc/apache2/mods-enabled/rewrite.load存在且内容为LoadModule rewrite_module modules/mod_rewrite.so - 关键一步:必须在站点配置中显式允许 .htaccess 覆盖,否则即使模块开着也无效。找到你的
块,在DocumentRoot下方加:
(路径按实际调整)AllowOverride All Require all granted - 重启服务:
systemctl restart apache2
,别只 reload
nginx 里“开启 rewrite”其实是配 location + try_files
nginx 没有“rewrite 模块开关”的概念,它默认支持 rewrite 指令,但 Laravel、TP 等框架的“伪静态”依赖的是 try_files 回退到 index.php。404 是因为请求没落到 PHP 处理器,而是被 nginx 当作静态文件找不到了。
- 确保
location /块包含:location / { try_files $uri $uri/ /index.php?$query_string; } - 确认
location ~ \.php$块存在且正确指向fastcgi_pass(如127.0.0.1:9000或unix:/var/run/php/php8.1-fpm.sock) - 如果用了子目录部署(如
http://site.com/app/),try_files第三项得改成/app/index.php?$query_string,否则 PATH_INFO 解析错乱
PHP-FPM 自身不处理 rewrite,但配置错误会掩盖真实问题
有人改了 php.ini 或 www.conf 后“突然 404”,其实不是 rewrite 引起的——而是 FPM 没把请求传给 PHP,或者 PHP 返回了空响应被 nginx/Apache 当成 404。这类问题容易误判。
- 检查
fastcgi_param SCRIPT_FILENAME是否拼错(常见错写成SCRIPT_NAME),导致 PHP 找不到脚本文件 - FPM pool 配置中
security.limit_extensions默认只认.php,如果你用.php5或其他后缀,要手动加进去 - 日志比猜有用:
tail -f /var/log/apache2/error.log或journalctl -u php8.1-fpm -f,看到 “Primary script unknown” 就是路径问题,“No input file specified” 多半是SCRIPT_FILENAME错了
验证 rewrite 是否真生效的三个命令
别只看网页 404,有些情况 rewrite 规则其实在跑,只是逻辑写错了。用命令行直击底层:
立即学习“PHP免费学习笔记(深入)”;
- 查 Apache 当前加载模块:
apache2ctl -M | grep rewrite
(输出应含rewrite_module (shared)) - 测 nginx 配置语法并查看重写日志(临时加):
nginx -t && nginx -s reload
,然后在server块加rewrite_log on; error_log /var/log/nginx/rewrite.log notice;
(注意权限) - 用 curl 模拟请求,看响应头和 body:
curl -I http://localhost/about
,若返回HTTP/1.1 404 Not Found且无X-Powered-By: PHP,说明请求根本没进 PHP
AllowOverride、nginx 里漏了 try_files、或日志没开导致瞎猜。rewrite 本身不难,难在它藏在 Web 服务器层,而错误表现却像 PHP 应用挂了。











