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

单域名下无头WordPress+静态前端的NGINX配置异常排查

一、当前PHP文件被下载问题的排查与修复

1. 核心原因

在location ~* /wp-块中,try_files $uri $uri/ /index.php?$query_string的逻辑会优先返回已存在的静态文件(包括PHP文件),不会触发嵌套的PHP处理块,导致wp-login.php这类文件被直接下载。

2. 修复配置

调整location ~* /wp-的结构,确保PHP请求优先进入处理逻辑:

location ~* /wp- {
    root /var/www/html/php/website.com; # 统一设置WordPress根目录
    index index.php;

    # 优先匹配PHP文件,直接交由PHP-FPM处理
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
    }

    try_files $uri $uri/ /index.php?$query_string;
}

关键调整:

  • 将WordPress的root移到外层location ~* /wp-,避免嵌套块重复配置
  • 把PHP处理块放在try_files之前,NGINX会优先匹配PHP请求,跳过静态文件返回逻辑

3. 额外排查点

  • 检查WordPress目录权限:确保/var/www/html/php/website.com下的PHP文件权限正确,NGINX进程(通常为www-data)有读取权限
  • 验证fastcgi配置:确认snippets/fastcgi-php.conf中的fastcgi_param SCRIPT_FILENAME指向正确的WordPress文件路径

二、/shop、/my-account等特定URL的配置方案

1. 统一正则匹配方案(简洁高效)

通过一个正则location覆盖所有需要交由WordPress处理的路径:

# 静态文件优先处理
location / {
    root /var/www/html/node/website.com/_build;
    index index.html;
    try_files $uri $uri.html $uri/ /404/index.html;
}

# 所有WordPress相关路径统一处理
location ~* ^/(wp-|shop|my-account) {
    root /var/www/html/php/website.com;
    index index.php;

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
    }

    try_files $uri $uri/ /index.php?$query_string;
}

说明:正则^/(wp-|shop|my-account)会匹配所有以/wp-、/shop、/my-account开头的请求,确保这些路径走WordPress逻辑。

2. 独立前缀配置方案(便于差异化调整)

如果需要对不同路径单独配置规则,可使用前缀location:

# 静态文件优先处理
location / {
    root /var/www/html/node/website.com/_build;
    index index.html;
    try_files $uri $uri.html $uri/ /404/index.html;
}

# WordPress核心路径
location ~* /wp- {
    root /var/www/html/php/website.com;
    index index.php;

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
    }

    try_files $uri $uri/ /index.php?$query_string;
}

# 电商路径
location /shop {
    root /var/www/html/php/website.com;
    index index.php;

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
    }

    try_files $uri $uri/ /index.php?$query_string;
}

# 用户账户路径
location /my-account {
    root /var/www/html/php/website.com;
    index index.php;

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
    }

    try_files $uri $uri/ /index.php?$query_string;
}

说明:前缀location的匹配优先级高于通用的location /,会优先处理对应路径的请求。

3. 生效验证

修改配置后执行以下命令确保语法正确并重启服务:

nginx -t
systemctl reload nginx

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 16:44:58