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

求助:配置Nginx适配Express驱动的React版Ghost博客SPA路由

解决React SPA版Ghost博客的Nginx路由失效问题

我之前在DigitalOcean上部署Ghost + React SPA的时候也踩过这个路由坑,给你几个针对性的解决思路,应该能帮你搞定:

1. 区分Ghost API与SPA路由的Nginx配置

核心问题是要让Nginx明确知道哪些请求该交给Ghost处理,哪些该转发给React SPA。之前的try_files没生效,大概率是没排除Ghost的API和静态资源路径,导致请求被错误导向了React的index.html。

试试这个配置:

server {
    listen 80;
    server_name your-domain.com; # 替换成你的实际域名

    # 处理Ghost的API请求,转发到Ghost默认端口2368
    location /api/ {
        proxy_pass http://localhost:2368;
        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;
    }

    # 处理Ghost自带的静态资源(比如主题assets文件)
    location /assets/ {
        proxy_pass http://localhost:2368;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    # 核心:处理React SPA的所有路由请求
    location / {
        root /path/to/your/react/spa/build; # 替换成你的React构建产物目录
        try_files $uri $uri/ /index.html; # 所有找不到的资源都fallback到index.html
        index index.html;
    }
}

2. 检查权限与路径正确性

  • 确保Nginx有权限访问你的React build目录:
    sudo chmod -R 755 /path/to/your/react/spa/build
    sudo chown -R www-data:www-data /path/to/your/react/spa/build
    
  • 先测试配置是否有语法错误,没问题再重启Nginx:
    sudo nginx -t
    sudo systemctl restart nginx
    

3. 确认React路由模式

如果你用的是BrowserRouter(不带#的美观路由),才需要Nginx的fallback配置;如果是HashRouter,路由逻辑会完全在前端处理,不需要Nginx调整。检查你的React代码里的路由组件,确保是符合预期的路由模式。

4. 查看Nginx错误日志排查问题

如果还是不行,去看Nginx的错误日志找具体线索:

tail -f /var/log/nginx/error.log

当你访问失效的SPA路由时,日志会显示Nginx尝试访问的文件路径,帮你快速定位是路径错误、权限问题还是配置逻辑漏洞。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:11:49