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

Nginx多子目录配置问题:双WordPress站点博客无法访问

解决Nginx下子目录WordPress站点无法访问的问题

我先梳理下你遇到的核心问题:主站https://optshare.com正常运行,但部署在/var/www/html/blog的子目录WordPress站点https://optshare.com/blog无法访问,且尝试过多种ServerFault方案未解决。结合这类场景的常见坑,我给你整理几个关键排查点和可行的配置方案:

一、先排查基础配置误区

1. 区分root和alias的正确用法

很多人在子目录配置里会混淆这两个指令,这是最常见的错误。如果你的博客目录是/var/www/html/blog,在location /blog块里应该用alias而不是root——因为root会把URI路径拼接到目录后,变成/var/www/html/blog/blog,显然不对。

2. 确保WordPress的站点URL设置正确

登录主站后台(或者直接修改博客目录下的wp-config.php),确认两个关键参数:

define('WP_HOME', 'https://optshare.com/blog');
define('WP_SITEURL', 'https://optshare.com/blog');

如果之前是按根目录配置的,这个设置不修改的话,WordPress会生成错误的资源路径,导致页面加载异常。

二、完整的Nginx配置示例

下面是针对你的场景优化后的配置,直接替换或整合到现有配置中:

server {
    listen 443 ssl;
    server_name optshare.com;

    # SSL相关配置(保留你原有的即可)
    ssl_certificate /path/to/your/cert.pem;
    ssl_certificate_key /path/to/your/key.pem;

    # 主站根目录配置
    root /var/www/html;
    index index.php index.html index.htm;

    # 主站的WordPress重写规则
    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    # 子目录博客的关键配置
    location /blog {
        alias /var/www/html/blog;
        index index.php index.html index.htm;

        # 处理静态资源,避免转发到PHP
        location ~ ^/blog/(.+\.(jpg|jpeg|gif|css|png|js|ico|html|xml|txt))$ {
            alias /var/www/html/blog/$1;
            expires max;
            access_log off;
        }

        # 博客的PHP处理规则
        location ~ ^/blog/.+\.php$ {
            alias /var/www/html/blog;
            fastcgi_pass unix:/run/php/php7.4-fpm.sock; # 根据你的PHP版本调整
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $request_filename;
            include fastcgi_params;
        }
    }

    # 全局PHP处理(主站用)
    location ~ \.php$ {
        try_files $uri =404;
        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;
    }
}

三、额外排查步骤

  • 权限检查:确保/var/www/html/blog目录及其文件的所有者是Nginx运行用户(通常是www-data),执行命令:
    sudo chown -R www-data:www-data /var/www/html/blog
    sudo chmod -R 755 /var/www/html/blog
    
  • 清除缓存:WordPress的缓存、浏览器缓存都要清空,避免旧的路径缓存导致异常。
  • Nginx语法检查:修改配置后一定要验证并重启:
    sudo nginx -t
    sudo systemctl restart nginx
    

四、为什么之前的方案可能无效?

很多ServerFault的方案是通用场景,但可能没考虑到:

  • 主站和子站都是WordPress,重写规则会互相干扰,需要明确区分各自的location块优先级
  • 没有正确处理子目录下的PHP请求,导致SCRIPT_FILENAME参数错误
  • 忽略了WordPress本身的站点URL配置,即使Nginx正确,WordPress也会生成错误链接

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:19:33