一、地址重写
地址重写即url重写,例如我们访问一个公司的某个地址,若公司决定临时维护这个地址的内容,那么公司可以运用地址重写的功能将用户访问的地址重定向到另一个地址,当维护结束后再取消这个重定向.
或者当一个公司的决定更换自己主页面地址,然后用户已经习惯了默认的地址,那么公司可以使用重定向技术将这个网址转到新的地址,直到用户熟悉这个新地址.
对于不同用户来说,他们使用的浏览器是不同的,有ie,firefox,chrome,那么根据市场占有率的不同,使用浏览器的人群占比也不同,如果使用firefox的用户占比90%,那么我们可以将服务器主要用于服务这个浏览器,那么对于其他浏览器的请求,可以使用少量服务器,这样更有利于监控网络流量等信息.
关于Nginx服务器的地址重写,主要用到的配置参数是rewrite:
- rewrite regex replacement flag
- rewrite 旧地址 新地址 [选项]
1.任务
- [对单个地址]所有访问a.html的请求,重定向到b.html;
- [对所有地址]所有访问192.168.4.5/下面子页面,重定向至www.tmooc.cn/下相同的页面;
- 实现firefox与chrome访问相同页面文件,返回不同的内容。
2.修改配置文件(访问a.html重定向到b.html)
做一个b.html,a.html即使不存在也可以,因为在访问a.html之前nginx就跳转到b.html下了
- [root@proxy ~]# vim /usr/local/nginx/conf/nginx.conf
- .. ..
- server {
- listen 80;
- server_name localhost;
- rewrite /a.html /b.html; //写到server下即可
- location / {
- root html;
- index index.html index.htm;
- }
- }
- [root@proxy ~]# echo "BB" > /usr/local/nginx/html/b.html
- [root@proxy ~]#firefox 192.168.4.5/a.html //如果访问a.html看到b.html的内容,证明实验成功
补充:这个地方我们做的是请求转发,也就是服务器将你对a.html的请求,转发给b.html,由b.html回应你,所有我们看到的结果是b.html下的内容,留意地址栏,地址并没有改变,仍然是192.168.4.5/a.html,如果你向做一个重定向,在rewrite /a.html /b.html; 后面追加一个属性redirect.
3.修改配置文件(访问192.168.4.5/下面子页面,重定向至www.csdn.net/下相同的页面)
- [root@proxy ~]# vim /usr/local/nginx/conf/nginx.conf
- .. ..
- server {
- listen 80;
- server_name localhost;
- rewrite ^/(.*)$ http://www.csdn.net/$1; //^/(.*)$正者表达式,匹配任意内容 $1代表^/(.*)$
- location / {
- root html;
- index index.html index.htm;
- }
- }
- [root@proxy ~]#firefox 192.168.4.5 //访问这个会跳转到http://www.csdn.net页面
补充:上面例子是对单个地址,这里是对多个地址
4.修改配置文件(实现谷歌和火狐访问相同链接返回的页面不同)
创建目录文件
- [root@proxy ~]# mkdir -p /usr/local/nginx/html/chrome/
- [root@proxy ~]# echo "chrome page" > /usr/local/nginx/html/chrome/test.html
- [root@proxy ~]# mkdir -p /usr/local/nginx/html/firefox/
- [root@proxy ~]# echo "firefox page" > /usr/local/nginx/html/firefox/test.html
修改配置文件
- [root@proxy ~]# vim /usr/local/nginx/conf/nginx.conf
- .. ..
- server {
- listen 80;
- server_name localhost;
- location / {
- root html;
- index index.html index.htm;
- }
- #这里,~符号代表正则匹配,*符号代表不区分大小写
- if ($http_user_agent ~* firefox) { //识别客户端firefox浏览器
- rewrite ^(.*)$ /firefox/$1;
- }
- }
测试:
- [root@proxy ~]# google-chrome 192.168.4.5/test.html
- [root@proxy ~]# firefox 192.168.4.5/test.html
这里有一点小问题,就是用谷歌浏览器的时候,内容显示会有点问题,大家可以尝试自己解决一下,解决不了可以在下面留言
5.地址重写格式
格式:
rewrite 旧地址 新地址 [选项];
选项:
last 不再读其他rewrite
break 不再读其他语句,结束请求
redirect 临时重定向
permament 永久重定向