12.9 Nginx域名重定向

时间:2022-04-27
本文章向大家介绍12.9 Nginx域名重定向,主要内容包括Nginx域名重定向目录概要、Nginx域名重定向、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

Nginx域名重定向目录概要

  • 更改test.com.conf
server
{
    listen 80;
    server_name test.com test1.com test2.com;
    index index.html index.htm index.php;
    root /data/wwwroot/test.com;
    if ($host != 'test.com' ) {
        rewrite  ^/(.*)$  http://test.com/$1  permanent;
    }
}
  • server_name后面支持写多个域名,这里要和httpd的做一个对比
  • permanent为永久重定向,状态码为301,如果写redirect则为302

Nginx域名重定向

  • 在Nginx里“server_name” 支持跟多个域名;但是Apache“server_name”只能跟一个域名,需要跟多个域名,需要使用Alisa;
  • 在Nginx的conf配置文件里“server_name ” 设置了多个域名,就会使网站的权重变了,到底需要哪个域名为主站点,所以需要域名重定向
  1. 修改配置文件vim /usr/local/nginx/conf/vhost/test.com.conf,(这里删除用户认证那一块代码)
[root@hf-01 vhost]# vim test.com.conf

server
{
    listen 80;
    server_name test.com test1.com test2.com;
    index index.html index.htm index.php;
    root /data/wwwroot/test.com;
    if ($host != 'test.com' ) {
        rewrite  ^/(.*)$  http://test.com/$1  permanent;
    }
}
保存退出
  • if ($host != ‘test.com’ ) //假如域名,“!=”不等于 test.com,将执行下面的脚本
  • rewrite ^/(.)$ http://test.com/$1 permanent; // ^/(.)$ 正式写法 http://$host/(.*)$ 这段可以直接省略掉的,同时还可以加上一些规则,
  • permanent 就是301的意思
  • 如果想弄成302,只需要更改为 redirect
  1. 检查配置文件语法错误,并重新加载配置文件
[root@hf-01 vhost]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@hf-01 vhost]# /usr/local/nginx/sbin/nginx -s reload
[root@hf-01 vhost]# 
  1. 测试,用test2.com去访问,会看到显示301,给它重定向到了http://test.com/index.html
[root@hf-01 vhost]# curl -x127.0.0.1:80 test2.com/index.html -I
HTTP/1.1 301 Moved Permanently
Server: nginx/1.12.1
Date: Wed, 03 Jan 2018 22:23:52 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: http://test.com/index.html

[root@hf-01 vhost]# 
  1. 定义一个不同的网址再来测试访问
[root@hf-01 vhost]# curl -x127.0.0.1:80 test2.com/admin/index.html -I
HTTP/1.1 301 Moved Permanently
Server: nginx/1.12.1
Date: Wed, 03 Jan 2018 22:25:57 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: http://test.com/admin/index.html

[root@hf-01 vhost]# 
  1. 它会访问默认虚拟主机
  2. 这时若是随意访问一个不存在的网址,则会显示404
[root@hf-01 vhost]# curl -x127.0.0.1:80 hanfeng.com/admin/index.html -I
HTTP/1.1 404 Not Found
Server: nginx/1.12.1
Date: Wed, 03 Jan 2018 22:27:37 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive

[root@hf-01 vhost]#