LNMP如何使用地址重写

一、地址重写

  地址重写即url重写,例如我们访问一个公司的某个地址,若公司决定临时维护这个地址的内容,那么公司可以运用地址重写的功能将用户访问的地址重定向到另一个地址,当维护结束后再取消这个重定向.

  或者当一个公司的决定更换自己主页面地址,然后用户已经习惯了默认的地址,那么公司可以使用重定向技术将这个网址转到新的地址,直到用户熟悉这个新地址.

  对于不同用户来说,他们使用的浏览器是不同的,有ie,firefox,chrome,那么根据市场占有率的不同,使用浏览器的人群占比也不同,如果使用firefox的用户占比90%,那么我们可以将服务器主要用于服务这个浏览器,那么对于其他浏览器的请求,可以使用少量服务器,这样更有利于监控网络流量等信息.

关于Nginx服务器的地址重写,主要用到的配置参数是rewrite:

  • rewrite regex replacement flag
  • rewrite 旧地址 新地址 [选项]

 

1.任务

  1. [对单个地址]所有访问a.html的请求,重定向到b.html; 
  2. [对所有地址]所有访问192.168.4.5/下面子页面,重定向至www.tmooc.cn/下相同的页面;
  3. 实现firefox与chrome访问相同页面文件,返回不同的内容。

 

2.修改配置文件(访问a.html重定向到b.html)

 做一个b.html,a.html即使不存在也可以,因为在访问a.html之前nginx就跳转到b.html下了

  1. [root@proxy ~]# vim /usr/local/nginx/conf/nginx.conf
  2. .. ..
  3. server {
  4. listen 80;
  5. server_name localhost;
  6. rewrite /a.html /b.html;             //写到server下即可
  7.  
  8. location / {
  9.     root html;
  10. index index.html index.htm;
  11. }
  12. }
  13.  
  14. [root@proxy ~]# echo "BB" > /usr/local/nginx/html/b.html
  15. [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/下相同的页面)

  1. [root@proxy ~]# vim /usr/local/nginx/conf/nginx.conf
  2.  
  3. .. ..
  4. server {
  5. listen 80;
  6. server_name localhost;
  7. rewrite ^/(.*)$  http://www.csdn.net/$1;  //^/(.*)$正者表达式,匹配任意内容 $1代表^/(.*)$
  8. location / {
  9.     root html;
  10. index index.html index.htm;
  11. }
  12. }
  13. [root@proxy ~]#firefox 192.168.4.5         //访问这个会跳转到http://www.csdn.net页面

补充:上面例子是对单个地址,这里是对多个地址

 

4.修改配置文件(实现谷歌和火狐访问相同链接返回的页面不同)

创建目录文件

  1. [root@proxy ~]# mkdir -p /usr/local/nginx/html/chrome/
  2. [root@proxy ~]# echo "chrome page" > /usr/local/nginx/html/chrome/test.html
  3. [root@proxy ~]# mkdir -p /usr/local/nginx/html/firefox/
  4. [root@proxy ~]# echo "firefox page" > /usr/local/nginx/html/firefox/test.html

修改配置文件

  1. [root@proxy ~]# vim /usr/local/nginx/conf/nginx.conf
  2. .. ..
  3. server {
  4. listen 80;
  5. server_name localhost;
  6. location / {
  7.     root html;
  8. index index.html index.htm;
  9. }
  10. #这里,~符号代表正则匹配,*符号代表不区分大小写
  11. if ($http_user_agent ~* firefox) {            //识别客户端firefox浏览器
  12. rewrite ^(.*)$ /firefox/$1;
  13. }
  14. }

测试:

  1. [root@proxy ~]# google-chrome 192.168.4.5/test.html
  2. [root@proxy ~]# firefox 192.168.4.5/test.html

这里有一点小问题,就是用谷歌浏览器的时候,内容显示会有点问题,大家可以尝试自己解决一下,解决不了可以在下面留言

 

5.地址重写格式

格式:

rewrite 旧地址 新地址 [选项];

选项:

last 不再读其他rewrite

break 不再读其他语句,结束请求

redirect 临时重定向

permament 永久重定向

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值