如何配置Nginx使所有场景返回Laravel 404而非Nginx错误
解决Nginx下所有请求均返回Laravel 404错误的配置方案
你当前的问题核心是:PHP结尾的请求、.env这类隐藏文件触发的错误会返回Nginx原生的404/403,而非Laravel统一的404页面。原因是这两类请求被对应的Nginx location块优先处理,没走到Laravel的入口逻辑。
关键修改方向
- 让不存在的PHP请求转由Laravel处理
- 把隐藏文件的直接拒绝规则改为转发到Laravel入口
- 覆盖403错误的处理逻辑,统一指向Laravel
修改后的完整Nginx配置
server { listen 80; listen [::]:80; server_name example.com; root /srv/example.com/public; add_header X-Frame-Options "SAMEORIGIN"; add_header X-Content-Type-Options "nosniff"; index index.php; charset utf-8; location / { try_files $uri $uri/ /index.php?$query_string; } location = /favicon.ico { access_log off; log_not_found off; } location = /robots.txt { access_log off; log_not_found off; } # 让404、403错误都走Laravel入口 error_page 404 403 /index.php; # PHP请求先检查文件是否存在,不存在则转Laravel处理 location ~ \.php$ { try_files $uri /index.php?$query_string; fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name; include fastcgi_params; } # 隐藏文件不再直接拒绝,转Laravel处理 location ~ /\.(?!well-known).* { try_files $uri /index.php?$query_string; } }
改动说明
- PHP请求处理:在
location ~ \.php$块中新增try_files $uri /index.php?$query_string;,当指定的PHP文件不存在时,直接转发到Laravel入口,由Laravel返回统一404。 - 隐藏文件处理:替换原有的
deny all;为try_files $uri /index.php?$query_string;,让.env这类请求也走Laravel逻辑(Laravel本身也会保护.env文件不被直接访问,双重保障)。 - 错误页扩展:将
error_page覆盖到403错误,确保所有权限类错误也返回Laravel的404页面。
修改完成后,执行sudo nginx -t验证配置合法性,确认无误后执行sudo systemctl reload nginx使配置生效。
内容的提问来源于stack exchange,提问作者Evan
相关产品推荐
相关产品推荐

