Nginx地址重写(重定向)

使用 “rewrite 旧地址 新地址 [redirect]”,来让地址重定向,其中redirect为可选项,表示浏览器地址栏的url是否发生变化。

	例1:访问www.a.com/a.html------->www.a.com/b.html
	vim /usr/local/nginx/conf/nginx.conf
	
	server {
        listen       80;	#端口
        server_name  www.a.com;		#虚拟主机
        rewrite /a.html 	/b.html;		#www.a.com/a.html		www.a.com/b.html
        location / {
            root   html;		# documentRoot
            index  index.html index.htm;	# 默认是index.html页面
        } 
     }
     还需要配置域名www.a.com,可以通过配置dns或者修改/etc/hosts


	例2:访问192.168.4.20------->www.baidu.com
	vim /usr/local/nginx/conf/nginx.conf
	
	server {
        listen       80;	#端口
        server_name  localhost;		#虚拟主机
        rewrite ^/ 	http://www.baidu.com;		#其中^代表正则表达式,^/表示所有路径
        location / {
            root   html;		# documentRoot
            index  index.html index.htm;	# 默认是index.html页面
        } 
     }


	例3:访问192.168.4.20/xxxxx------->www.baidu.com/xxxxx
	vim /usr/local/nginx/conf/nginx.conf
	
	server {
        listen       80;	#端口
        server_name  localhost;		#虚拟主机
        rewrite ^/(.*) 	http://www.baidu.com/$1;	#其中^代表正则表达式,^/(.*)表示提取所有路径,然后通过$1使用匹配到的路径
        location / {
            root   html;		# documentRoot
            index  index.html index.htm;	# 默认是index.html页面
        } 
     }

	例4:实现不同的浏览器访问192.168.4.20/test.html返回不同的页面
	这里咱们使用curl浏览器和firefox浏览器。curl是一款没有图形的浏览器,只可以显示代码信息。

首先看配置文件:
在这里插入图片描述
然后看登录日志 /usr/local/nginx/logs/access.log
xxx.xx.xxx.xx - - [20/Sep/2019:23:08:54 +0800] “GET /poweredby.png HTTP/1.1” 404 555 “http://xx.xx.xx.xx/” “Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36”

	其中配置文件的变量$http_user_agent 对应日志中的
	"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36"
	Safari代表浏览器的类型。
	因此只需要在配置文件中让变量 $http_user_agent 和对应的浏览器进行模糊匹配就可以了
	if ($http_user_agent ~* firefox) {		# 其中~代表正则,*代表忽略大小写,注意if后的空格
		rewrite ^/(.*)		/firefox/$1;		# 同案例3
	}
	mkdir /var/local/nginx/html/firefox
	echo 'firefox page!!' >  /var/local/nginx/html/firefox/test.html
	echo 'normal page!!!!' >  /var/local/nginx/html/test.html
	
	重启niginx服务。nginx -s reload

写总结的第十六天!!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值