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

WordPress迁移Nginx遇301重定向问题:求配置排查

问题分析与修复方案

你的Nginx配置缺少WordPress运行必需的核心规则,结合AWS ALB的SSL场景,主要问题点及修复方案如下:

1. 缺失WordPress URL重写规则

Apache通过.htaccess自动处理WordPress的友好URL路由,但Nginx需要显式配置请求转发逻辑。当前配置没有将非静态文件/目录的请求导向index.php,导致WordPress无法解析页面路由。

修复:在server块中添加以下location配置

location / {
    try_files $uri $uri/ /index.php?$args;
}

# PHP处理规则(根据你的PHP-FPM实际路径调整)
location ~ \.php$ {
    fastcgi_pass unix:/run/php-fpm/www.sock; # 也可能是127.0.0.1:9000
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

2. 未正确处理ALB的HTTPS转发头

AWS ALB已配置SSL重定向,但Nginx没有向WordPress传递HTTPS请求的标识,导致WordPress生成HTTP协议的链接,触发ALB再次重定向到HTTPS,形成循环301。

修复:

  • 在server块中添加转发头处理:
# 信任ALB的IP段(根据你的VPC CIDR调整)
set_real_ip_from 10.0.0.0/8;
real_ip_header X-Forwarded-For;
real_ip_recursive on;

# 传递HTTPS标识给WordPress
fastcgi_param HTTP_X_FORWARDED_PROTO $http_x_forwarded_proto;
fastcgi_param HTTPS $http_x_forwarded_proto = 'https' ? 'on' : 'off';
  • 同时修改WordPress的wp-config.php,强制HTTPS:
define('WP_HOME', 'https://你的实际域名');
define('WP_SITEURL', 'https://你的实际域名');
define('FORCE_SSL_ADMIN', true);

if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
    $_SERVER['HTTPS'] = 'on';
}

3. server_name配置优化

当前server_name _是通用匹配,建议改为你的实际域名,避免潜在的匹配冲突:

server_name your-domain.com www.your-domain.com;

完整示例server块

server {
    listen       80;
    listen       [::]:80;
    server_name  your-domain.com www.your-domain.com;
    root         /var/www/html/;

    # 信任ALB转发头
    set_real_ip_from 10.0.0.0/8;
    real_ip_header X-Forwarded-For;
    real_ip_recursive on;

    # WordPress路由规则
    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    # PHP处理
    location ~ \.php$ {
        fastcgi_pass unix:/run/php-fpm/www.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param HTTP_X_FORWARDED_PROTO $http_x_forwarded_proto;
        fastcgi_param HTTPS $http_x_forwarded_proto = 'https' ? 'on' : 'off';
        include fastcgi_params;
    }

    include /etc/nginx/default.d/*.conf;

    error_page 404 /404.html;
    location = /404.html {
    }
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
    }
}

配置修改后,重启Nginx服务:sudo systemctl restart nginx,同时确保PHP-FPM服务正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 04:47:03