301重定向是永久性重定向,对SEO友好,会将原始URL的权重传递给新URL。以下是几种在Nginx中实现301跳转的方法:
server {
listen 80;
server_name example.com;
location /old-page {
return 301 http://example.com/new-page;
}
}
server {
listen 80;
server_name old-domain.com;
return 301 http://new-domain.com$request_uri;
}
server {
listen 80;
server_name example.com;
return 301 http://www.example.com$request_uri;
}
server {
listen 80;
server_name www.example.com;
return 301 http://example.com$request_uri;
}
server {
listen 80;
server_name example.com www.example.com;
return 301 https://example.com$request_uri;
}
server {
listen 80;
server_name example.com;
rewrite ^/old-url$ http://example.com/new-url permanent;
# 或者
rewrite ^/old-path/(.*)$ http://example.com/new-path/$1 permanent;
}
return 301
比rewrite
更高效,推荐优先使用nginx -s reload
$request_uri
可以保留原始请求的URI和参数修改配置后,可以使用以下命令测试:
curl -I http://example.com/old-url
应该能看到类似这样的响应:
HTTP/1.1 301 Moved Permanently
Location: http://example.com/new-url
301重定向会被浏览器缓存,测试时可能需要清除浏览器缓存或使用隐私模式。