Ubuntu服务器Nginx带Hash的WordPress重置密码URL重定向问题
Nginx WordPress重置密码URL重定向解决重定向过多问题
问题描述
搭建重置密码服务时遇到以下问题:
- API发送给用户的重置密码URL为
https://mydomain.com.mx/?hash=hash_code,需要将其重定向到https://mydomain.com.mx/recovery/?hash=hash_code - 尝试过
rewrite、try_files等配置,其中最接近的配置是:
但出现**too many redirects(重定向过多)**错误if ($arg_hash) { return 301 https://mydomain.com.mx/recovery/?hash=$arg_hash; } - 站点基于WordPress搭建,无法修改API发送的原始URL
问题原因
原配置的条件$arg_hash会匹配所有带hash参数的请求,包括重定向后的/recovery/?hash=xxx,导致每次访问重定向后的URL都会再次触发重定向,形成无限循环。
解决方案
需要限定仅根路径(/)且存在hash参数时才执行重定向,修改Nginx配置如下:
找到原配置中注释掉的if块,替换为:
location = / { if ($arg_hash) { return 301 https://mydomain.com.mx/recovery/?hash=$arg_hash; } }
或者也可以用更紧凑的写法(效果相同):
if ($request_uri = /?hash=$arg_hash) { return 301 https://mydomain.com.mx/recovery/?hash=$arg_hash; }
配置说明
location = /是精准匹配根路径的请求,只有当用户访问https://mydomain.com.mx/?hash=xxx时才会进入这个块- 结合
$arg_hash的判断,确保只对根路径带hash参数的请求执行重定向,避免了循环问题 - 重定向后访问
/recovery/?hash=xxx时,因为请求路径不是根路径,不会触发该规则,循环被打破
完整修改后配置片段
在server块中添加上述规则即可,完整server块关键部分示例:
server { root /var/www/html/mydomain.com.mx; access_log /var/log/nginx/mydomain.com.mx.access.log custom; error_log /var/log/nginx/mydomain.com.mx.error.log debug; index index.html index.htm index.nginx-debian.html index.php; server_name www.mydomain.com.mx mydomain.com.mx; # ... 其他已有配置 ... # 新增的重定向规则 location = / { if ($arg_hash) { return 301 https://mydomain.com.mx/recovery/?hash=$arg_hash; } } location / { try_files $uri $uri/ /index.php?$args; } # ... 其他已有配置 ... }
内容的提问来源于stack exchange,提问作者Brayan Martinez Espinosa
相关产品推荐
相关产品推荐

