Nginx配置域名重定向/域名跳转

以上一篇文章搭建的个人博客网站为例,当前域名test.blog.com,新增一个域名www.blog.com指向到该网站

nginx配置多个域名:

编辑nginx虚拟主机配置文件:

[root@linux ~]# vi /etc/nginx/conf.d/default.conf 

在server_name项新增域名www.blog.com:
Nginx配置域名重定向/域名跳转_第1张图片
验证配置并重载:

[root@linux ~]# nginx -t && nginx -s reload

接下来即可通过新域名www.blog.com访问该网站:
Nginx配置域名重定向/域名跳转_第2张图片
nginx配置域名重定向/跳转:

编辑nginx虚拟主机配置文件:

[root@linux ~]# vi /etc/nginx/conf.d/default.conf 

添加如下内容:

    if ( $host = test.blog.com )
        {
           rewrite /(.*) http://www.blog.com/$1 permanent;
        }

验证配置并重载:

[root@linux ~]# nginx -t && nginx -s reload
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

测试:

[root@linux ~]# curl -x127.0.0.1:80  -I test.blog.com
HTTP/1.1 301 Moved Permanently
Server: nginx/1.16.1
Date: Sun, 13 Oct 2019 15:24:43 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Location: http://www.blog.com/

#http状态码301,Location: http://www.blog.com/,对test.blog.com的请求已成功跳转到www.blog.com,对于搜索引擎来说,test.blog.com被认为是旧域名,而优先访问新域名www.blog.com

永久重定向:permanent http状态码:301 (域名重定向使用,转移域名权重)
临时重定向:redirect http状态码:302 (非域名跳转使用,比如文件跳转)

编辑nginx虚拟主机配置文件:

[root@linux ~]# vi /etc/nginx/conf.d/default.conf 

nginx添加文件跳转:

rewrite /1.txt /2.txt redirect;

验证配置并重载:

[root@linux ~]# nginx -t && nginx -s reload
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

测试:

[root@linux ~]# curl -x127.0.0.1:80  -I www.blog.com/1.txt
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.16.1
Date: Sun, 13 Oct 2019 15:45:17 GMT
Content-Type: text/html
Content-Length: 145
Location: http://www.blog.com/2.txt
Connection: keep-alive

#http状态码:302,Location: http://www.blog.com/2.txt,文件跳转成功

你可能感兴趣的:(Nginx)