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

NGINX部署React站点子目录WordPress后内页404问题求助

问题解决:NGINX子目录部署WordPress内页404

错误根源分析

你的NGINX配置存在3个核心问题:

  • fastcgi_split_path_info规则里写的是/wordpress,但实际WordPress部署在/blog目录,路径匹配错误
  • try_files最后回退的/index.php未添加/blog前缀,导致NGINX去根目录找WordPress入口文件,而非/blog目录下的
  • 嵌套的PHP location中,fastcgi_split_path_info的正则表达式有误,且fastcgi_param的顺序和重复引用存在冲突

修正后的完整NGINX配置

server {
    root /var/www/html;
    index index.php index.html index.htm index.nginx-debian.html;
    server_name domain.com;

    # React主站配置
    location / {
        try_files $uri $uri/ /index.html; # React单页应用需回退到index.html,原配置的=404会导致前端路由跳转404
    }

    # WordPress子目录配置
    location ^~ /blog {
        client_max_body_size 10m;

        # 处理无结尾斜杠的URL重定向
        rewrite ^(/blog[^/]+)$ $1/ permanent;

        # 尝试匹配文件/目录,否则回退到blog下的index.php
        try_files $uri $uri/ /blog/index.php?$args;

        location ~ \.php$ {
            try_files $uri =404;
            # 修正路径拆分规则,适配/blog目录下的PHP文件
            fastcgi_split_path_info ^(/blog)(/.*\.php)(.*)$;
            fastcgi_index index.php;
            fastcgi_pass unix:/run/php/php8.1-fpm.sock;
            # 正确指定PHP脚本的物理路径
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param PATH_INFO $fastcgi_path_info;
            include fastcgi_params;
        }
    }

    listen [::]:443 ssl ipv6only=on; 
    listen 443 ssl; 
    # ssl certificates here
}

关键修改说明

  1. React主站调整:把location /里的=404改为/index.html,确保React单页应用的前端路由能正常工作
  2. URL重定向优化:用rewrite替代原有的if规则,符合NGINX最佳实践,避免if指令的潜在问题
  3. 路径匹配修正:
    • try_files回退路径改为/blog/index.php?$args,确保指向WordPress的正确入口
    • fastcgi_split_path_info的正则改为^(/blog)(/.*\.php)(.*)$,正确拆分/blog目录下的PHP文件路径
  4. 参数顺序调整:先定义SCRIPT_FILENAME和PATH_INFO,再引入fastcgi_params,避免被默认参数覆盖

WordPress后台配套设置

登录WordPress后台,进入设置→常规:

  • 站点地址(URL):设置为https://domain.com/blog
  • WordPress地址(URL):设置为https://domain.com/blog
    然后进入设置→固定链接,选择除“朴素”外的任意格式(比如“文章名”),保存设置,让WordPress生成正确的内页链接规则

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 19:45:39