在Nginx中配置fastcgi_pass对接PHP-FPM,核心是确定PHP-FPM的运行模式(Unix Socket或TCP端口)并在nginx.conf的location块中正确指向它。通常推荐优先使用Unix Socket以获得更低延迟和更高安全性;若需跨进程或容器通信,则使用127.0.0.1:9000等TCP地址。确保Nginx用户有权限访问Socket文件或防火墙允许TCP连接即可。

确认PHP-FPM监听方式与路径
先检查php-fpm.conf或pool配置文件中的listen指令,判断当前使用的是socket文件或TCP端口。这是配置fastcgi_pass的前提条件。

打开PHP-FPM的pool配置文件(通常位于/etc/php/*/fpm/pool.d/www.conf),查找listen行。如果值为类似/var/run/php/php7.4-fpm.sock的路径,说明使用的是Unix Socket;如果值为127.0.0.1:9000或:::9000,则使用的是TCP端口。对于Ubuntu/Debian系统,默认通常是socket;CentOS/RHEL可能默认为TCP。务必根据实际配置调整Nginx中的fastcgi_pass值,否则会导致502 Bad Gateway错误。
配置Nginx fastcgi_pass指令
在Nginx服务器配置文件中,为.php文件添加location块,并将fastcgi_pass设置为上一步确认的地址。同时必须包含fastcgi_params参数传递脚本信息。

# Nginx Configuration Example for PHP-FPM
# This snippet goes inside the server block of your nginx.conf
server {
listen 80;
server_name example.com;
root /var/www/html;
# Default location
location / {
try_files $uri $uri/ =404;
}
# Handle PHP files
location ~ \.php$ {
include snippets/fastcgi-php.conf;
# Option 1: Using Unix Socket (Recommended for local performance)
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
# Option 2: Using TCP Port (Use this if socket fails or for remote FPM)
# fastcgi_pass 127.0.0.1:9000;
}
}
# To apply changes:
# sudo nginx -t
# sudo systemctl reload nginx
# Verify PHP-FPM is listening on the configured address:
# ss -lnx | grep php-fpm.sock # For socket
# ss -lnt | grep :9000 # For TCP port
该配置片段展示了如何在Nginx中通过fastcgi_pass指令连接PHP-FPM。注释中提供了两种常见连接方式:Unix Socket和TCP端口。实际使用时,只需保留其中一行有效配置并删除另一行的注释符号#。保存配置后,通过sudo nginx -t验证语法,再reload生效。若遇到502错误,请对照程序下方的验证命令检查PHP-FPM是否确实在指定地址监听。
编辑/etc/nginx/sites-available/default或相应的server块配置。找到处理PHP的location ~ \.php$ 块。将fastcgi_pass的值修改为对应的socket路径或IP:端口。例如,若使用socket,写fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;;若使用TCP,写fastcgi_pass 127.0.0.1:9000;。确保include fastcgi_params;存在,以便传递SCRIPT_FILENAME等关键变量。修改后运行sudo nginx -t测试配置语法,无误后sudo systemctl reload nginx重载服务。
排查502 Bad Gateway常见原因
配置完成后若出现502错误,通常是因为Nginx无法连接到PHP-FPM指定的地址,或者权限不足、服务未启动。
检查PHP-FPM服务是否正在运行:systemctl status php*-fpm。确认Nginx用户(如www-data)对Socket文件有读写权限,若无权限可chmod或chown调整,或改用TCP避免权限问题。若使用TCP,确认9000端口未被其他进程占用且防火墙放行。查看Nginx错误日志tail -f /var/log/nginx/error.log获取具体失败原因,如Connection refused表示目标未监听,Permission denied表示权限缺失。