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

如何在Nginx上共存PHP站点与Next.js路由,解决访问异常

解决方案

问题1:PHP文件被直接下载

你的PHP处理块缺少核心配置,导致Nginx未将PHP请求转发给PHP-FPM解析。修改location ~ \.php$块:

location ~ \.php$ {
    try_files $uri =404;  # 恢复该行,拦截恶意请求不存在的PHP文件
    include snippets/fastcgi-php.conf;  # 恢复该行,加载PHP处理的关键参数配置
    fastcgi_pass unix:/var/run/php7.4-fpm.sock;
    include fastcgi_params;
}

原因:snippets/fastcgi-php.conf中定义了SCRIPT_FILENAME等FastCGI必需参数,缺少它时PHP-FPM无法识别待执行的脚本,Nginx会直接将PHP文件作为静态资源返回。


问题2:/blog页面资源加载异常

Next.js默认运行在根路径下,通过mysite.com/blog访问时,页面资源会请求根路径下的/_next/...,但这些请求会被Nginx转发给PHP站点,导致资源丢失。调整反向代理配置如下:

location /blog {
    rewrite ^/blog/(.*)$ /$1 break;
    proxy_pass http://127.0.0.1:3000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}

原因:

  1. rewrite规则将/blog/xxx转换为/xxx转发给Next.js,匹配它的原始路由结构
  2. proxy_set_header Host $host让Next.js感知当前域名,生成正确的资源链接
  3. 其余X-Forwarded-*头用于让Next.js获取客户端真实IP与请求协议

完整修正后的Nginx配置

server {
    listen 80;
    listen [::]:80;

    root /var/www/nginx/mysite;
    index index.html index.htm index.nginx-debian.html index.php;  # 添加index.php到默认索引,支持直接访问PHP首页

    server_name mysite.com www.mysite.com;

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

    location ~ \.php$ {
        try_files $uri =404;
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php7.4-fpm.sock;
        include fastcgi_params;
    }

    location /blog {
        rewrite ^/blog/(.*)$ /$1 break;
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

生效步骤

  1. 保存修改后的配置文件
  2. 验证配置合法性:sudo nginx -t
  3. 重启Nginx:sudo systemctl restart nginx

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 02:00:33