本文最后更新于9 天前,其中的信息可能已经过时,如有错误请发送邮件到nahrice@qq.com
问题原因
- 重定向循环
- 当访问
https://nahrice.cn/wp-admin/
时,WordPress 检测到X-Forwarded-Proto: https
,但可能因代理头未正确传递或 WordPress 配置冲突,导致无限重定向。
- 当访问
- 资源路径混合
- 当
siteurl
设为http://localhost:8080
时,WordPress 生成的静态资源(CSS/JS)链接为http://localhost:8080/...
,浏览器因安全策略阻止加载非 HTTPS 资源。
- 当
解决方案
1. 修正 Nginx 代理配置
更新 nginx.conf
,确保 WordPress 路径正确代理:
location / {
proxy_pass http://127.0.0.1:8080;
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; # 必须:告知 WordPress 这是 HTTPS
proxy_set_header X-Forwarded-Host $host; # 防止域名误判
client_max_body_size 0;
}
2. 强制 WordPress 使用 HTTPS
在 wp-config.php
中添加以下代码(覆盖所有可能的路径判断):
在 wp-config.php 中,所有自定义定义 必须 放在 require_once ABSPATH . 'wp-settings.php'; 之前(即 "stop editing" 注释之前):
php
/* Add any custom values between this line and the "stop editing" line. */
define('WP_HOME', 'https://nahrice.cn');
define('WP_SITEURL', 'https://nahrice.cn');
define('FORCE_SSL_ADMIN', true);
$_SERVER['HTTPS'] = 'on';
// 修复代理服务器变量
if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) {
$_SERVER['HTTP_HOST'] = $_SERVER['HTTP_X_FORWARDED_HOST'];
}
/* That's all, stop editing! Happy publishing. */
3. 清理数据库残留路径
执行以下 SQL(通过 phpMyAdmin 或 wp-cli
):
UPDATE wp_options SET option_value = 'https://nahrice.cn' WHERE option_name IN ('siteurl', 'home');
UPDATE wp_posts SET post_content = REPLACE(post_content, 'http://localhost:8080', 'https://nahrice.cn');
4. 清除所有缓存
- WordPress:禁用缓存插件(如 WP Super Cache)。
- 浏览器:按
Ctrl+Shift+Del
清除缓存和 Cookie。 - Nginx:重启服务
nginx -s reload
。
验证是否成功
- 访问
https://nahrice.cn/wp-admin/
→ 应直接进入登录页,无重定向。 - 检查浏览器开发者工具(Network):
- 所有资源请求的域名应为
https://nahrice.cn
,无localhost:8080
。 - 无
Mixed Content
警告(所有资源均为 HTTPS)。
- 所有资源请求的域名应为
常见问题排查
现象 | 原因 | 解决方案 |
---|---|---|
仍无限重定向 | Cookie 或 Session 冲突 | 在 wp-config.php 中添加: define('COOKIE_DOMAIN', 'nahrice.cn'); |
502 Bad Gateway | XAMPP 未运行或端口冲突 | 确保 127.0.0.1:8080 的 Apache 已启动 |