找回密码
 新建账号

nginx PATH_INFO 404 GetFileAttributesEx() 错误

[复制链接]
php 发表于 2024/6/9 13:17 | 显示全部楼层 |阅读模式
nginx fastcgi_pass 将请求传递给 PHP 处理时,需要在 fastcgi_params 中定义 PATH_INFO,PHP 脚本才可以拿到 PATH_INFO,nginx 官方提供的原始 fastcgi_params 中没有配置 PATH_INFO。
实际操作中,nginx 直接报了 404 错误,根本没把请求传递给 PHP。
其实是因为没有正确配置 nginx,导致 nginx 把有 PATH_INFO 的请求的伪路径当成了真实路径。
比如请求以下 URI
  1. /index.php/foo/bar
复制代码
真正的脚本文件是网站根目录中的 index.php 而不是网站根目录中的 index.php/foo/bar。
要正确识别 PATH_INFO,需要正确处理 URI。
  1. location ~* "\.php" {
  2.     fastcgi_connect_timeout 3;
  3.     fastcgi_index index.php;
  4.     fastcgi_pass 127.0.0.1:10086;
  5.     fastcgi_split_path_info "^(.*\.php)(.*)$";
  6.     include fastcgi_params;
  7. }
复制代码
fastcgi_split_path_info 将 URI 分割成两个部分,第一个部分作为 PHP 脚本的文件路径,保存在 nginx 变量 $fastcgi_script_name 中,第二个部分作为 PATH_INFO,保存在 nginx $fastcgi_path_info 中。
在 fastcgi_params 中加入以下配置
  1. fastcgi_param PATH_INFO $fastcgi_path_info;
复制代码
在 fastcgi_params 中加入或修改为以下配置
  1. fastcgi_param SCRIPT_NAME $fastcgi_script_name;
  2. fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
复制代码
在生效的 php.ini 中加入或修改为以下配置
  1. cgi.fix_pathinfo = 1
复制代码
如果 nginx 错误日志中出现以下错误
  1. 2024/06/09 11:34:44 [crit] 14036#1616: *3 GetFileAttributesEx() "C:\server\www\wuxiancheng\index.php/" failed (123: The filename, directory name, or volume label syntax is incorrect), client: 127.0.0.1, server: wuxiancheng.cn, request: "GET /index.php/ HTTP/2.0", host: "www.wuxiancheng.cn"
复制代码
说明配置错误,导致 URI 切割错误,将 / 切给了 PHP 的文件路径。

需要注意的是,以上 location 配置块中不能有 try_files,否则也会直接导致 404 找不到文件。
如果有下面这样的配置,需要将它删除。
  1. try_files $uri $uri/ =404;
复制代码
删除 try_files 会导致另外一个问题,就是 PHP 文件不存在时,nginx 无法按配置处理 404 错误,而只能返回 PHP 的错误信息。
在 location 配置块中加入以下配置拦截 PHP 错误。这会拦截由 PHP 返回的状态码大于 300 的错误。
  1. fastcgi_intercept_errors on;
复制代码
相关链接 fastcgi_split_path_info fastcgi_intercept_errors cgi.fix_pathinfo

手机版|轻松E站

GMT+8, 2024/7/27 18:53

快速回复 返回顶部 返回列表