You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

树莓派Nginx反向代理下Node.js Express向PHP发AJAX POST遇问题

问题分析与解决办法

一、PHP文件被下载而非执行的问题

问题根源在于你把Nginx 80端口的所有请求都反向代理到了Express,导致所有请求先经过Node.js处理——Express会把.php文件当作普通静态资源直接返回,完全没机会让PHP-FPM解析它。你之前在/var/www/html配置的PHP解析规则,在反向代理生效后已经不作用于当前请求路径了。

解决步骤:

  1. 修改Nginx配置文件(比如/etc/nginx/sites-available/default),在反向代理的location /块之前,添加专门处理/private/scripts/下PHP文件的规则:
location ~ /private/scripts/.*\.php$ {
    root /your/express/project/root/path; # 替换成你的Express项目根目录(即private文件夹所在的路径)
    fastcgi_pass unix:/run/php/php7.4-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}
  1. 保留原有的反向代理配置:
location / {
    proxy_pass http://localhost:3000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}
  1. 重启Nginx生效:sudo systemctl restart nginx

这样Nginx会优先把/private/scripts/下的PHP请求交给PHP-FPM解析,其他请求再转发给Express。

二、AJAX POST报404的问题

问题出在相对路径错误:触发请求的页面是http://localhost/private/index.html,AJAX用相对路径"restart.php"时,实际请求的是http://localhost/private/restart.php,但你的PHP文件在private/scripts/restart.php,路径不匹配导致404。

解决步骤:
修改AJAX的请求路径为正确的相对路径或绝对路径:

function restart_server() {
    let request = new XMLHttpRequest();

    request.onload = function() {
        if (this.status >= 200 && this.status < 400) {
            console.log("success");
        } else {
            console.log("error");
        }
    }

    request.onerror = function () {
        console.log("error");
    }

    request.open("POST", "scripts/restart.php", true); // 修正为正确的相对路径
    request.send();
}

也可以直接用绝对路径"/private/scripts/restart.php",避免页面路径变化带来的问题。

内容的提问来源于stack exchange,提问作者Azus Dkk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 08:33:35