应使用Nginx配置301永久重定向将shop.example.com/buy?id=12345&sku=SKU001迁移至trade.example.com/product/12345/purchase?sku=SKU001,需精确匹配路径、校验参数、记录日志并全面验证。

明确需要迁移的旧链接格式和新链接规则
旧版电商系统中数字商品购买链接通常类似:
https://shop.example.com/buy?id=12345&sku=SKU001
新版交易链路统一走语义化路径,例如:
https://trade.example.com/product/12345/purchase?sku=SKU001
关键点:域名变更(shop → trade)、路径重写(/buy → /product/{id}/purchase)、查询参数保留(如 sku)、必须用 301 永久重定向 告知搜索引擎和客户端链接已永久迁移。
在 Nginx 配置中精准匹配并重写 URL
在对应 server 块(通常是 shop.example.com 的配置)中添加 location 和 rewrite 规则:
- 用 location = /buy 精确匹配旧路径,避免误伤其他 /buy* 接口
- 用 rewrite 提取 query 参数中的 id 和 sku,拼装新 URL;使用 $arg_id 和 $arg_sku 直接读取参数值
- 添加 permanent 标志,等价于 301(不加则为临时重定向)
示例配置片段:
server {
listen 80;
server_name shop.example.com;
<pre class="brush:php;toolbar:false;">location = /buy {
if ($arg_id = "") {
return 400 "Missing required parameter: id";
}
rewrite ^(.*)$ https://trade.example.com/product/$arg_id/purchase?sku=$arg_sku permanent;
}}
处理参数缺失、非法 ID 或跳转失败的兜底逻辑
仅靠 rewrite 不足以覆盖所有异常场景,建议补充:
- 用 if ($arg_id !~ ^\d+$) 拦截非纯数字 ID,返回 400 或跳转到错误页
- 若新版服务暂未就绪,可先指向维护页(return 302 /maintenance.html),避免 5xx 波及用户
- 记录重定向日志:在 location 内添加 access_log /var/log/nginx/buy_redirect.log main;,便于后续分析迁移效果
验证与上线注意事项
上线前务必验证三类行为:
- 正常请求:
curl -I "http://shop.example.com/buy?id=999&sku=DIGI2024"→ 应返回 HTTP/1.1 301 Moved Permanently 及正确 Location 头 - 缺参请求:
?id=或无 id → 应返回 400,不跳转 - 浏览器访问后检查地址栏是否刷新为新域名新路径,且新版页面能正确加载商品信息
上线后监控 Nginx error log 中的 rewrite 警告,并观察新版交易链路的 UV/PV 是否同步上升,确认流量已平稳承接。











