fastcgi_pass必须写在location块内,用于将.php请求转发至PHP-FPM,需配合include fastcgi_params、fastcgi_param SCRIPT_FILENAME等指令,并确保监听地址一致、路径安全、文件存在性校验。

在 Nginx 中,fastcgi_pass 用于将 PHP 请求转发给 FastCGI 进程(如 PHP-FPM),它必须写在 location 块内,且通常配合 fastcgi_param 等指令使用,才能正确解析和传递 PHP 脚本。
location 匹配 PHP 文件的常见写法
要让 Nginx 把 .php 请求交给 PHP-FPM 处理,需用正则或前缀匹配 PHP 文件。推荐使用更安全的精确匹配方式,避免恶意构造文件名绕过:
-
location ~ \.php$ { ... }:匹配以 .php 结尾的 URI(最常用) -
location ~ ^/index\.php(/|$) { ... }:只匹配 /index.php 及其 PATH_INFO(更严格) - 避免
location ~ \.php(不加 $),否则可能匹配到 user.php.jpg 等非脚本文件
fastcgi_pass 必须指向有效的 PHP-FPM 地址
fastcgi_pass 后跟的是 PHP-FPM 的监听地址,可以是 Unix socket 或 TCP 地址:
- Unix socket:
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; - TCP 地址:
fastcgi_pass 127.0.0.1:9000; - 确保 PHP-FPM 正在运行,且监听地址与这里配置一致(检查
php-fpm.conf或 pool 配置中的listen =)
必需的 fastcgi_param 参数不能遗漏
仅写 fastcgi_pass 不够,PHP-FPM 需要关键环境变量才能定位脚本并执行。至少包含:
立即学习“PHP免费学习笔记(深入)”;
-
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;(推荐用$realpath_root防路径穿越) fastcgi_param QUERY_STRING $query_string;fastcgi_param REQUEST_METHOD $request_method;fastcgi_param CONTENT_TYPE $content_type;fastcgi_param CONTENT_LENGTH $content_length;
建议直接引入官方提供的 fastcgi_params 文件(通常位于 /etc/nginx/fastcgi_params),再覆盖或补充关键项:
include fastcgi_params; fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
配合 try_files 防止任意代码执行
为避免 Nginx 将不存在的 .php 文件也转发给 PHP-FPM(可能导致泄露源码或执行恶意文件),应在 location 块中加入 try_files:
-
try_files $fastcgi_script_name =404;:确保 PHP 文件真实存在,否则返回 404 - 更严谨写法:
try_files $uri =404;放在 server 块中,再由 location ~ \.php$ 接管已存在的 .php 请求 - 注意:若使用
alias指令,$fastcgi_script_name可能不准确,优先用$realpath_root+$fastcgi_script_name
配置完成后记得重载 Nginx:nginx -t && systemctl reload nginx,并确认 PHP-FPM 服务状态正常。



















