当页面搬家、更换域名或强制启用 HTTPS 时,重定向可以保住访客和搜索排名。本教程介绍如何在您的 VPS Linux Infrawire 上编写规范的 Nginx 重定向,并在上线前完成测试。
📋 前提条件
- 一台可通过 SSH 以 root 登录的 Linux VPS(Ubuntu 24.04 / Debian 12 或 AlmaLinux 9 / Rocky 9)。IP 和 root 密码可在客户中心找到。
- 已安装 Nginx 并至少托管一个站点(
sudo apt install nginx或sudo dnf install nginx)。 - 一个域名(
example.com),其 DNS A/AAAA 记录指向VPS_IP。
🧭 301 还是 302
- 301(Moved Permanently):永久搬迁。浏览器和搜索引擎会缓存它,并把排名权重转移到新网址。
- 302(Found):临时搬迁(维护、A/B 测试)。旧网址仍是基准。
拿不准时先用 302:错误的 301 可能在浏览器缓存里停留很久。
⚙️ return 还是 rewrite
优先使用 return:Nginx 会立即停止处理,因此更快、更易读。
Nginxlocation = /old-page { return 301 /new-page; }
只有需要用正则表达式捕获网址的一部分时才使用 rewrite:
Nginxrewrite ^/blog/(\d+)/(.*)$ /articles/$2 permanent;
标志 permanent 返回 301,redirect 返回 302。
🌐 将 www 重定向到非 www
创建一个只负责跳转的独立 server 块。编辑 /etc/nginx/sites-available/example.com(Debian/Ubuntu)或 /etc/nginx/conf.d/example.com.conf(AlmaLinux/Rocky):
Nginx1server { 2 listen 80; 3 listen [::]:80; 4 server_name www.example.com; 5 return 301 $scheme://example.com$request_uri; 6}
如需相反方向,把两个主机名互换即可。$request_uri 会保留路径和查询字符串。
🔒 将 HTTP 重定向到 HTTPS
安装证书后,把所有明文流量转到 HTTPS:
Nginx1server { 2 listen 80; 3 listen [::]:80; 4 server_name example.com www.example.com; 5 return 301 https://example.com$request_uri; 6} 7 8server { 9 listen 443 ssl; 10 listen [::]:443 ssl; 11 http2 on; 12 server_name www.example.com; 13 ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; 14 ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; 15 return 301 https://example.com$request_uri; 16}
真正的站点放在第三个监听 443、server_name example.com; 的块中。注意 http2 on; 需要 Nginx 1.25.1 或更高版本,Ubuntu 24.04 满足该条件。
🔗 旧网址到新网址
只有少数页面时,使用最快的精确匹配(=):
Nginxlocation = /about-us.html { return 301 /about; } location = /promo { return 302 /offers/current; }
对于整个搬迁的目录并保留子路径:
Nginxlocation /docs/ { rewrite ^/docs/(.*)$ /help/$1 permanent; }
🏠 重定向整个域名
当您弃用 old-example.com 改用 example.com 时,保留全部路径:
Nginx1server { 2 listen 80; 3 listen [::]:80; 4 server_name old-example.com www.old-example.com; 5 return 301 https://example.com$request_uri; 6}
如果旧域名也启用了 HTTPS,请添加对应的 listen 443 ssl; 块并配置其自己的证书,否则浏览器会在跳转前先显示证书错误。
✅ 测试并安全重载
重载前务必先校验语法。reload 会保留现有连接,restart 则不会。
Bashsudo nginx -t sudo systemctl reload nginx
然后在不跟随跳转的情况下检查响应头:
Bashcurl -I http://www.example.com/old-page
预期输出(节选):
HTTP/1.1 301 Moved Permanently
Server: nginx
Location: https://example.com/old-page
要跟随整条链并查看每一跳,请使用 curl -IL http://www.example.com/old-page。理想情况是只有一跳:避免 HTTP、再 www、再 HTTPS 这样的链条。
🛠️ 故障排查
重定向次数过多(循环)。 某条规则匹配到了自己的目标,常见原因是代理或 CDN 已经终止了 HTTPS。用 curl -I 检查 Location 头,并确认目标块不会再次跳转。
修改没有生效。 您编辑的文件没有被启用。在 Debian/Ubuntu 上检查 /etc/nginx/sites-enabled/ 中的链接,然后运行 sudo nginx -t 和 sudo systemctl reload nginx。浏览器也会缓存 301:请用 curl 或隐私窗口测试。
查询字符串丢失。 使用 rewrite ... ? 或固定目标时参数会消失。请在 return 中使用 $request_uri,或显式保留 $args。
响应的块不对。 Nginx 按 server_name 选择块。用 sudo nginx -T | grep server_name 列出它们并查找重复项。
🎉 您的重定向已生效:确定的用永久,不确定的用临时,并在访客察觉之前用 curl 测试完毕。