重定向(Redirect)是将用户请求从一个URL自动转发到另一个URL的过程。在网站迁移、域名更换或内容重组时,重定向是确保用户体验和SEO价值不流失的关键技术。
return 302 https://newdomain.com$request_uri;
return 301 https://newdomain.com$request_uri;
server {
listen 80;
server_name olddomain.com www.olddomain.com;
return 301 https://newdomain.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;
return 301 $scheme://www.example.com$request_uri;
}
location /old-path/ {
return 301 /new-path/;
}
location ~* ^/products/(.*)$ {
return 301 /shop/$1;
}
if ($args ~* "^param=([^&]+)") {
return 301 https://newdomain.com/newpath?custom=$1;
}
if ($http_user_agent ~* "bot|spider|crawler") {
return 301 https://newdomain.com/bots/$request_uri;
}
geo $redirect_geo {
default 0;
US 1;
UK 2;
}
server {
if ($redirect_geo = 1) {
return 301 https://us.newdomain.com$request_uri;
}
if ($redirect_geo = 2) {
return 301 https://uk.newdomain.com$request_uri;
}
}
bash
curl -I http://olddomain.com/path
server {
listen 80;
server_name oldsite.com www.oldsite.com;
# 重定向所有HTTP到HTTPS
return 301 https://newsite.com$request_uri;
}
server {
listen 443 ssl;
server_name oldsite.com www.oldsite.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
# 特定路径重定向
location /legacy/ {
return 301 https://newsite.com/modern/$request_uri;
}
# 其他请求重定向
location / {
return 301 https://newsite.com$request_uri;
}
}
通过合理配置Nginx重定向,您可以平滑地将流量从旧网站转移到新网站,同时保持搜索引擎排名和用户体验。