用rewrite规则实现将所有到a域名的访问rewrite到b域名

1、临时重定向

1.1使用redirect实现临时重定向

# cat /apps/nginx/conf/nginx.conf
...省略...
 server {
        listen          80; 
        server_name     www.a.com;
        location / { 
            root        /data/nginx/html/a;
            index       index.html index.htm;
            rewrite /   http://www.b.com redirect;
        }   
    }   

    server {
        listen          80; 
        server_name     www.b.com;
        location / { 
            root        /data/nginx/html/b;
            index       index.html index.htm;
        }   

    }   

1.2 测试

#curl www.a.com
<html>
<head><title>302 Found</title></head>
<body>
<center><h1>302 Found</h1></center>
<hr><center>nginx/1.18.0</center>
</body>
</html>
#curl www.a.com -Ik
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.18.0
Date: Sun, 28 Nov 2021 07:47:55 GMT
Content-Type: text/html
Content-Length: 145
Connection: keep-alive
Location: http://www.b.com

win10端测试,添加www.a.com的本地域名解析

2、永久重定向

2.1 使用permanent实现临时重定向

# cat /apps/nginx/conf/nginx.conf
...省略...
 server {
        listen          80; 
        server_name     www.a.com;
        location / { 
            root        /data/nginx/html/a;
            index       index.html index.htm;
            rewrite /   http://www.b.com permanent;
        }   
    }   

    server {
        listen          80; 
        server_name     www.b.com;
        location / { 
            root        /data/nginx/html/b;
            index       index.html index.htm;
        }   

    }   

2.2 访问测试

#curl www.a.com -Ik
HTTP/1.1 301 Moved Permanently
Server: nginx/1.18.0
Date: Sun, 28 Nov 2021 08:01:40 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Location: http://www.b.com

#curl www.a.com
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.18.0</center>
</body>
</html>

可以看出临时重定向的状态码是302,而永久重定向的状态码是301

posted @ 2022-01-13 20:42  火火7412  阅读(83)  评论(0编辑  收藏  举报