要在 nginx rewrite 中显式丢弃旧 get 参数,关键在于不将 $args 或 $request_uri 带入 replacement 字符串;正确写法为 rewrite ^/old/(.*)$ /new/$1 last,或用 return 301 /new/$1 实现绝对干净跳转。

要在 Nginx 的 rewrite 规则中显式丢弃旧的 GET 参数(即清除查询字符串 $args),关键在于**不将 $args 或 $request_uri 带入 replacement 字符串**,并避免使用会自动继承参数的行为。
明确不携带参数的重写方式
默认情况下,Nginx 的 rewrite 指令只操作 URI 路径部分(即 $uri),不会自动拼接原始查询参数。只要 replacement 中不显式引用 $args、$request_uri 或 $is_args$args,参数就不会被保留。
- ✅ 正确(丢弃参数):
rewrite ^/old/(.*)$ /new/$1 last;
→ 请求/old/a?x=1&y=2重写为/new/a,无参数 - ❌ 错误(保留参数):
rewrite ^/old/(.*)$ /new/$1?$args last;
→ 显式拼接了$args,参数被带过去 - ⚠️ 注意:
rewrite ^/old/(.*)$ /new/$1 permanent;仍会返回 301,但浏览器重定向时可能因缓存或客户端行为附带原参数;若需彻底剥离,应确保 replacement 不含?且不触发外部跳转(见下条)
用 return 替代 rewrite 实现绝对干净跳转
当目标是强制清除参数并返回重定向响应时,return 比 rewrite ... permanent 更可控 —— 它完全绕过 rewrite 流程,直接构造响应地址:
-
return 301 /new/$1;→ 不含?,浏览器跳转到/new/xxx,无任何参数 -
return 301 https://example.com/new/$1;→ 协议+域名+路径全指定,$args绝对不参与 - 对比:
rewrite ^/old/(.*)$ https://example.com/new/$1 permanent;行为相同,但return语义更清晰、执行更早、不依赖 rewrite 匹配链
配合 if 判断主动清空参数场景
若需“有参数才丢弃”,比如仅当存在特定参数时重写并去参,可用 if + return 组合:
-
if ($args ~ "utm_source=") { return 301 $scheme://$host$request_uri; }→ 这里仍带参,不对 - 正确写法:
if ($args ~ "utm_source=") { return 301 $scheme://$host/real/path; }
→ 直接写死目标路径,不引用$request_uri或$args - 更稳妥:
if ($args) { return 301 $scheme://$host$uri; }
→ 用$uri(不含参数)替代$request_uri,确保干净
验证与调试建议
启用 rewrite 日志可确认参数是否被带入:
- 在 http/server/location 块中加:
rewrite_log on;和error_log /path/to/error.log notice; - 查看日志中是否出现类似
using regex "^/old/(.*)$" ... rewritten to "/new/$1"—— 若 replacement 字段不含?或$args,即已丢弃 - 用 curl 测试:
curl -I "http://domain/old/test?x=1",观察Location:头是否含?











