在Nginx中同时使用不同PHP版本遇阻:请求均被PHP5.5处理
问题分析与修复方案
你的问题核心是Nginx的location匹配优先级、路径映射(root/alias)以及try_files逻辑导致/reports路径下的请求没有正确进入PHP8.0的处理块,反而落到了PHP5.5的配置里。以下是具体问题点和修复后的配置:
关键问题点
- 正则location匹配与路径映射错误:
你用了location ~ ^/reports正则匹配,但搭配alias /var/www/html/会导致路径拼接错误——比如请求/reports/test.php会被映射到/var/www/html/test.php而非预期的/var/www/html/reports/test.php,文件不存在时直接返回404,最终请求可能被兜底的location /接管。 - try_files逻辑阻止PHP处理:
第一个location里的try_files $uri =404会直接返回静态文件或404,不会将PHP请求转发到嵌套的PHP处理块。 - alias在location /下的隐患:
location /使用alias会导致路径处理逻辑复杂,容易出现$document_root拼接错误,进而影响PHP脚本的路径解析。
修复后的Nginx配置
server { listen 80 default_server; listen [::]:80 default_server; server_name $NGINX_HOST; index index.php index.html; error_log /var/log/nginx/error.log; access_log /var/log/nginx/access.log; # 处理PHP8.0的/reports应用 location ^~ /reports { root /var/www/html; # /reports/test.php 对应 /var/www/html/reports/test.php index index.php; # 优先访问文件→目录→跳转index.php,确保PHP请求能进入处理块 try_files $uri $uri/ /reports/index.php?$args; location ~ \.php$ { fastcgi_pass php8.0:9000; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } } # 处理PHP5.5的旧系统 location / { root /var/www/html/oldSystem; # 用root替代alias,路径逻辑更直观 index index.php; try_files $uri $uri/ /index.php?$args; location ~ \.php$ { fastcgi_pass php5.5:9000; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } } }
核心修改说明
location ^~ /reports:使用^~前缀匹配,优先级高于所有正则location,确保/reports开头的请求不会被其他配置拦截。- 替换
alias为root:root的路径映射逻辑更简单直接,避免alias带来的路径拼接错误,PHP脚本的路径解析更可靠。 - 调整
try_files:添加$uri/和跳转index.php的逻辑,既保证静态文件正常访问,又能让PHP请求正确进入嵌套的处理块。 - 修正
SCRIPT_FILENAME:去掉多余斜杠,避免出现//这类无效路径,确保PHP-FPM能正确找到脚本文件。
内容的提问来源于stack exchange,提问作者Dmitry Shumsky
相关产品推荐
相关产品推荐

