Nginx地址重写

                                                                                                             Nginx地址重写


适用范围:

因域名地址可能会因为其他原因更换,而客户因为习惯之前域名,可能会难以适应,故需进行地址重写,可实现网页目录的跳转和域名的跳转,从而增加客户接受能力。


格式:

rewrite 旧地址 新地址 [选项]

1.修改配置文件

# vim /usr/local/nginx/conf/nginx.conf

.. ..

server {

listen       80;

server_name  localhost;

location / {

root   html;

index  index.html index.htm;

rewrite /a.html  /b.html  redirect;                  【注意空格】

}

}

*****    redirect                                                 【可加可不加,添加后可以在地址栏上看到地址的跳转】

2.重起服务

# /usr/local/nginx/sbin/nginx  -s  reload

可利用正则进行设置

示例:

#access_log  logs/host.access.log  main;

rewrite ^/ http://www.baidu.com/;                  【尖角号/ 为判断为包含/即可跳转】

location / {

root   html;

index  index.html index.htm;

# rewrite /a.html /b.html redirect;

}

二)实现跳转相同页面  【用户访问网页内容可得到相应内容】

1.修改配置文件:

#access_log  logs/host.access.log  main;

rewrite ^/(.*) http://www.baidu.com/&1;

location / {

root   html;

index  index.html index.htm;

# rewrite /a.html /b.html redirect;

}

(.*) 匹配所有【复制】

$1   粘贴

*********************************************************************************************************************

  三)不同浏览器,访问相同页面,返回不同结果

1.需要准备两套页面

切换到存放网页的目录

# cd /usr/local/nginx/html

创建网页:

echo "curl" >  test.html

mkdir  firefox

echo "firefox" > firefox/test.html

2.修改配置文件

#access_log  logs/host.access.log  main;

#rewrite ^/(.*) http://www.tmooc.cn/&1;

if ($http_user_agent ~* firefox){ rewrite ^/(.*)$ /firefox/$1; 【首先用if语句对浏览器进行判断,然后确定是否对网页进行跳转】 【~* 为不区分大小写】

}

location / {

root   html;

index  index.html index.htm;

# rewrite /a.html /b.html redirect;

}

3.刷新服务

# /usr/local/nginx/sbin/nginx -s reload

4.测试

firefox 192.168.4.5/test.html

curl    192.168.4.5/test.html  【可以看到显示内容不同】



猜你喜欢

转载自blog.51cto.com/13713381/2114576