Azure App Service升级至PHP 8.1后Nginx持续返回404错误
我正尝试将CakePHP应用从PHP 7.4迁移至搭载PHP 8.1的Azure App Service环境,却无法配置出合适的Nginx参数使其正常运行。我基于基础Nginx配置,添加了CakePHP官方文档中的配置项,并在启动时通过命令cp /home/default /etc/nginx/sites-enabled/default注入配置文件。目前除根页面外,其他页面均返回404错误,根页面也因相关资源链接返回404出现布局异常。
当前使用的Nginx配置如下:
server { #proxy_cache cache; #proxy_cache_valid 200 1s; listen 8080; listen [::]:8080; #root /home/site/wwwroot; root /home/site/wwwroot/webroot; #index index.php index.html index.htm; index index.php; server_name example.com www.example.com; port_in_redirect off; #location / { # index index.php index.html index.htm hostingstart.html; #} # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root /html/; } # Disable .git directory location ~ /\.git { deny all; access_log off; log_not_found off; } #added from CakePHP book location / { try_files $uri $uri/ /index.php?$args; } #added from CakePHP book location ~ \.php$ { try_files $uri =404; include fastcgi_params; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_intercept_errors on; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } # Add locations of phpmyadmin here. #location ~ [^/]\.php(/|$) { # fastcgi_split_path_info ^(.+?\.php)(|/.*)$; # fastcgi_pass 127.0.0.1:9000; # include fastcgi_params; # fastcgi_param HTTP_PROXY ""; # fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; # fastcgi_param PATH_INFO $fastcgi_path_info; # fastcgi_param QUERY_STRING $query_string; # fastcgi_intercept_errors on; # fastcgi_connect_timeout 300; # fastcgi_send_timeout 3600; # fastcgi_read_timeout 3600; # fastcgi_buffer_size 128k; # fastcgi_buffers 4 256k; # fastcgi_busy_buffers_size 256k; # fastcgi_temp_file_write_size 256k; #} }
问题排查与修复方案
修复静态资源加载问题
确认root /home/site/wwwroot/webroot;路径正确,webroot下的CSS、JS、图片等静态文件存在且权限设置为Nginx进程可读取(通常是www-data用户组)。若静态资源路径无误,当前location /的try_files规则已能优先匹配静态文件,无需额外修改。调整PHP路由解析规则
原PHP配置块未处理PATH_INFO,导致CakePHP无法解析非根页面的路由。替换原PHP配置块为以下内容:location ~ \.php(/|$) { try_files $uri =404; include fastcgi_params; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_intercept_errors on; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; }新增的
fastcgi_split_path_info用于分离脚本文件和路由路径,这是CakePHP路由解析的必要配置。验证PHP-FPM监听地址
Azure App Service的PHP 8.1环境中,PHP-FPM可能未监听127.0.0.1:9000,而是使用Unix套接字。通过SSH连接实例,查看/etc/php/8.1/fpm/pool.d/www.conf中的listen配置项,若为套接字路径(如/run/php/php8.1-fpm.sock),则修改fastcgi_pass为对应路径。检查配置合法性并重启服务
修改配置后执行nginx -t验证配置语法,确认无错误后执行service nginx reload重启Nginx服务。排查CakePHP应用层问题
查看Azure App Service日志中心的应用日志,确认是否存在PHP 8.1兼容性错误(如废弃函数调用、类型声明不兼容等),同时检查config/routes.php中的路由配置是否正常。
内容的提问来源于stack exchange,提问作者TechFanDan

