Nginx域名重定向目录概要
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 ” 设置了多个域名,就会使网站的权重变了,到底须要哪一个域名为主站点,因此须要域名重定向
- 修改配置文件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
- 检查配置文件语法错误,并从新加载配置文件
[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]#
- 测试,用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]#
- 定义一个不一样的网址再来测试访问
[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]#
- 它会访问默认虚拟主机
- 这时如果随意访问一个不存在的网址,则会显示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]#