PAYATHON 2026

Windows 便携 Nginx 中相对 html 目录导致 PHP 不解析

数据小陈

结论:root ../html; 用来处理静态 HTML 一般没问题,Nginx 会按自己的 prefix 解析相对路径。但 PHP 请求要转给 php-cgi、FastCGI,而 PHP 进程按自己的工作目录解析 SCRIPT_FILENAME。如果传过去的是相对路径,就容易碰到 404、No input file specified 或 502。把 PHP 段的 SCRIPT_FILENAME 改成 $realpath_root$fastcgi_script_name,再确认 php-cgi.exe 正在 127.0.0.1:9000 监听,通常就能解决。

原因

静态请求由 Nginx 自己解析 root ../html;,所以 HTML 能正常打开。PHP 请求则通过 fastcgi_pass 127.0.0.1:9000; 交给 FastCGI 进程处理。原来的 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 在 root 是相对路径时,$document_root 未必是 php-cgi 期望的绝对路径,于是它找不到 ../html/xxx.php。还有一种情况:php-cgi.exe 压根没启动,这时会直接返回 502 Bad Gateway。这跟 root 用相对路径是两回事,排查时都要看。

修改 nginx.conf

把 PHP location 改成下面这样,重点是 SCRIPT_FILENAME 用 $realpath_root:

server {
    listen 80;
    server_name localhost;
    root ../html;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
    }

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root ../html;
    }
}

改完重载或重启 Nginx。Windows 下可以在 nginx 目录执行:

nginx.exe -s reload

如果没生效,先停掉再启动。

启动 php-cgi

在 portable-server 根目录下,先启动 php-cgi.exe:

php\php-cgi.exe -b 127.0.0.1:9000 -c php\php.ini

再启动 Nginx:

nginx\nginx.exe -p nginx -c conf\nginx.conf

确认 9000 端口在监听:

netstat -ano | findstr :9000

看到 LISTENING 才说明 php-cgi 起来了。9000 没监听时 PHP 请求会 502,这跟 Nginx 的 root 无关。

快速判断问题在哪

  • 502 Bad Gateway:先查 php-cgi.exe 有没有启动、端口是否一致、php.ini 路径对不对。
  • No input file specified 或 404:多半是 SCRIPT_FILENAME 不对。可以临时把 root 换成绝对路径试试,比如 root C:/portable-server/html;,同时用 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;。绝对路径能跑,就说明问题出在把相对路径传给了 PHP。
  • 浏览器直接下载 PHP 源码:看 location ~ \.php$ 是不是写在正确的 server {} 里,以及请求的 URI 是否真的以 .php 结尾。
  • PHP 页面报扩展缺失:查 php.ini 里的 extension_dir 和对应扩展有没有启用。这属于另一层问题,跟 Nginx 解析无关。

便携场景注意

USB 盘符变化时,静态文件用 root ../html; 仍然可用;PHP 段用 $realpath_root 就不用写死 C:/...。某些旧版或特殊构建对 $realpath_root 支持不完整,这时可以用 subst 给 USB 目录映射一个固定盘符,或者在 start.bat 里生成绝对路径配置,不过后者比相对路径麻烦。路径里有空格的话,批处理和配置里的路径要加引号,或者用支持空格的写法。

备注:内容仅供参考。