Nginx 301重定向实现平滑迁移需分三步:域名整体迁移用独立server块+return 301原样映射;路径调整用location+return或rewrite精准跳转;兼容旧请求需处理后缀、大小写等细节,并通过配置分离、语法检查与多场景测试确保生效。
Nginx 301 重定向在服务器迁移中要实现平滑过渡,关键是让每个旧请求精准、无损地抵达对应的新地址,既不丢参数,也不跳首页,更不能循环或降级协议。
域名整体迁移:用独立 server 块 + return 301
这是最常用也最稳妥的方式。旧域名所有流量(含路径和查询参数)必须原样映射到新域名对应位置。
server 块,分别监听 80 和 443 端口server_name 列出全部旧域名,比如 old.com www.old.com old.net
return 301 目标写死新地址,例如 https://new.com$request_uri
这样用户访问 http://old.com/product?id=7 或 https://www.old.com/blog/2024/,都会分别跳转为 https://new.com/product?id=7 和 https://new.com/blog/2024/,路径与参数毫发无损。
路径结构调整:用 location + return 或 rewrite
当新旧站点同域但目录变了(如 /news/ → /blog/),适合在新站的 server 块内配置:
单页精确跳转:
location = /old-contact.html {return 301 /contact/;}
目录批量迁移:
location ^~ /news/ {rewrite ^/news/(.*)$ /blog/$1 permanent;}
注意:permanent 是 rewrite 的 301 标志;location ^~ 比正则匹配更快,适合前缀类迁移。
保留客户端兼容性:特别处理常见旧请求
老旧客户端(如某些爬虫、APP 内嵌 WebView 或 IE8+)可能带特殊参数、大小写混用、或访问 .php 后缀页面。可针对性补规则:
强制统一后缀:
location ~ .php$ {rewrite ^(/.*?)(?:.php)(?.*)?$ $1$2 permanent;}
兼容大小写与分隔符:
rewrite ^/category/([a-z0-9_-]+)$ /categories/$1 permanent;
若新版 slug 无法预知(如数据库动态生成),先跳无 slug 版本,由后端二次跳转,避免 404。
配置管理与上线前验证
/etc/nginx/conf.d/redirects.conf),用 include 引入主配置nginx -t 检查语法 → nginx -s reload 生效(不中断服务)curl -I http://old.com/test?ref=abc:确认返回 301 Moved Permanently 和正确 Location 头不复杂但容易忽略。