在 Nginx 中实现重定向有多种方法,下面我将详细介绍几种常见的重定向方式及其配置方法。
server {
listen 80;
server_name olddomain.com;
return 301 http://newdomain.com$request_uri;
}
server {
listen 80;
server_name tempdomain.com;
return 302 http://maindomain.com$request_uri;
}
location /oldpath/ {
return 301 http://example.com/newpath/;
}
location /search {
return 301 http://example.com/newsearch$is_args$args;
}
server {
server_name www.example.com;
return 301 $scheme://example.com$request_uri;
}
server {
server_name example.com;
return 301 $scheme://www.example.com$request_uri;
}
server {
listen 80;
server_name example.com;
return 301 https://example.com$request_uri;
}
server {
rewrite ^/oldurl$ /newurl permanent; # 301 重定向
rewrite ^/tempurl$ /newurl redirect; # 302 重定向
}
if ($http_user_agent ~* "bot") {
rewrite ^(.*)$ /bot-page$1 last;
}
if ($remote_addr = 192.168.1.100) {
rewrite ^(.*)$ /special-page$1 last;
}
location /old-dir/ {
rewrite ^/old-dir/(.*)$ /new-dir/$1 permanent;
}
return
指令而不是 rewrite
,因为它更高效sudo nginx -t
sudo systemctl reload nginx
$scheme
变量可以自动匹配 http 或 https希望这些配置示例能帮助您实现所需的 Nginx 重定向功能!