try_files 是 nginx 文件查找核心指令,必须确保仅真实存在的 php 文件交由 php-fpm 执行,否则易引发 cve-2019-11043 等任意文件执行漏洞;推荐配置为 location ~ .php$ { try_files $uri =404; … },并禁用 cgi.fix_pathinfo。

try_files 是 Nginx 中控制请求文件查找顺序的核心指令,配合 PHP-FPM 使用时,关键在于**避免将不存在的路径误传给 PHP 解析器执行**——这是常见安全漏洞(如 CVE-2019-11043 或任意文件执行)的根源。正确配置的核心原则是:**只有真实存在的 PHP 文件才交由 fastcgi_pass 处理,其余一律 404 或拒绝。**
明确 try_files 的执行逻辑和常见误区
try_files 按空格分隔的列表依次检查路径是否存在(仅检查文件或目录,不触发后端);遇到最后一个参数(必须是非 URI 形式,如 @php 或 /index.php)时,若前面全失败,则内部重定向到该目标。
常见错误写法:try_files $uri $uri/ /index.php?$query_string; —— 这会让 /nonexistent.jpg/anything.php 这类路径最终落到 /index.php,而 PHP 可能因 PATH_INFO 解析不当执行恶意代码。
推荐的安全兜底配置(标准 PHP 应用)
以下配置确保:只对真实存在的 .php 文件调用 PHP-FPM,其他情况返回 404:
location ~ \.php$ {
# 仅当请求的 .php 文件真实存在时才继续
try_files $uri =404;
<pre class="brush:php;toolbar:false;"># 标准 FastCGI 参数
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass 127.0.0.1:9000; # 或 unix:/var/run/php/php8.2-fpm.sock}
支持前端路由(如 Vue Router、React Router)的混合场景
静态资源(JS/CSS/图片)和 API 接口走正常规则,HTML 兜底由 index.php 处理,但必须防止 PHP 文件被伪造路径触发:
# 静态资源直接返回,不进 PHP
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
<h1>PHP 脚本:严格校验文件存在</h1><p>location ~ .php$ {
try_files $uri =404;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
}</p><h1>前端路由兜底:仅当请求非文件/非目录且非 PHP 时,交给 index.php 处理</h1><p>location / {
try_files $uri $uri/ @html;
}</p><p>location @html {
rewrite ^(.*)$ /index.php?$1 last;
}</p><h1>确保 index.php 本身也受 try_files 保护</h1><p>location = /index.php {
try_files $uri =404;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
}</p>额外加固建议
- 禁用 PHP 的
cgi.fix_pathinfo=0(在 php.ini 中),彻底关闭 PATH_INFO 自动推导,从 PHP 层堵住解析漏洞 - 限制上传目录禁止执行 PHP:
location ^~ /uploads/ { location ~ \.php$ { return 403; } } - 使用
fastcgi_intercept_errors on;配合error_page 404 /404.html;统一错误页,避免泄露服务器信息
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











