nginx rewrite概述

跳转场景

URL看起来更规范合理
企业将动态URL地址伪装成静态地址提供服务
网址换新域名后,让旧的访问网址跳转到新的域名上
服务端某些业务调整

跳转实现

nginx 支持 tcp dubbo nginx 支持patch_字符串

跳转实现方式

使用rewrite进行匹配跳转
使用if匹配全局变量后跳转
使用location匹配再跳转

rewrite放在server{},if{},location{}段中
location只对域名后边的出去传递参数外的字符串起作用

对域名或参数字符串
使用if全局变量匹配
使用proxy_pass反向代理

nginx正则表达式

nginx 支持 tcp dubbo nginx 支持patch_字符串_02

rewrite命令

rewrite命令语法
rewrite (正则) (跳转后的内容) [flag] (rewrite支持的flag标记);

flag标记说明

nginx 支持 tcp dubbo nginx 支持patch_字符串_03

last和break比较

nginx 支持 tcp dubbo nginx 支持patch_html_04

location

分类
location = patt {} [精准匹配]
location patt {} [一般匹配]
location ~ patt {} [正则匹配]

正则匹配常用的表达式

nginx 支持 tcp dubbo nginx 支持patch_nginx 支持 tcp dubbo_05

location 优先级

相同类型的表达式,字符串长的会优先匹配

按优先级排列
=类型
^~类型表达式
正则表达式(和*)类型
常用字符串匹配类型、按前缀匹配(一般匹配)
通用匹配(/),如果没有其它匹配,任何请求都会匹配到

location优先级规则
匹配某个具体文件
(location = 完整路径)> (location ^~ 完整路径) > (location ~* 完整路径)= (location ~ 完整路径)> (location 完整路径) > (location /)
用目录做匹配访问某个文件
(location = 目录)> (location ^~ 目录/)> (location ~ 目录) = (location ~* 目录)> (location 目录) > (location /)

比较rewrite和location

都可以进行跳转
不同
rewrite是在同一域名内更改获取资源的路径
location是对一类路径做控制访问或反向代理,还可以proxy_pass到其它机器

rewrite会写在location里,执行顺序
执行server块里面的rewrite指令
执行location匹配
执行选定的location中的rewrite指令

基本应用

1

有新域名代替旧域名,在不能废除旧域名的情况下,从旧域名跳转到新域名,且保持参数不变

nginx 支持 tcp dubbo nginx 支持patch_html_06


nginx 支持 tcp dubbo nginx 支持patch_html_07


创建日志mkdir /var/log/nginx

创建网页文件

nginx 支持 tcp dubbo nginx 支持patch_字符串_08


nginx 支持 tcp dubbo nginx 支持patch_nginx_09

2

基于客户端ip地址的跳转

vi /etc/nginx.conf

nginx 支持 tcp dubbo nginx 支持patch_字符串_10


编辑要重定向的网页

vi /usr/local/nginx/html/new.html

nginx 支持 tcp dubbo nginx 支持patch_nginx 支持 tcp dubbo_11


再20主机下

nginx 支持 tcp dubbo nginx 支持patch_字符串_12


再其他主机下

nginx 支持 tcp dubbo nginx 支持patch_字符串_13

3

将域名bbs.ph.com下的所有发帖都跳转到www.ph.com,且域名跳转后保持参数不变

vi /etc/nginx.conf

nginx 支持 tcp dubbo nginx 支持patch_html_14


在服务器里创建bbs内的网页

nginx 支持 tcp dubbo nginx 支持patch_html_15


添加映射

nginx 支持 tcp dubbo nginx 支持patch_字符串_16


重启后访问测试

nginx 支持 tcp dubbo nginx 支持patch_nginx_17


nginx 支持 tcp dubbo nginx 支持patch_nginx_18

4

基于参数匹配的跳转

vi /etc/nginx.conf

nginx 支持 tcp dubbo nginx 支持patch_字符串_19


nginx 支持 tcp dubbo nginx 支持patch_nginx 支持 tcp dubbo_20


访问www.nph.com/100-100-10.html,会跳转www.nph.com

nginx 支持 tcp dubbo nginx 支持patch_nginx 支持 tcp dubbo_21


访问www.nph.com/100-300-10.html,超出匹配范围不会跳转www.nph.com

nginx 支持 tcp dubbo nginx 支持patch_nginx 支持 tcp dubbo_22

5

基于目录下所有php文件跳转

vi /etc/nginx.conf

nginx 支持 tcp dubbo nginx 支持patch_nginx 支持 tcp dubbo_23


nginx 支持 tcp dubbo nginx 支持patch_字符串_24


重启后测试

nginx 支持 tcp dubbo nginx 支持patch_nginx_25

基于最普通url请求的跳转

vi /etc/hosts

nginx 支持 tcp dubbo nginx 支持patch_html_26


重启后测试

访问http://www.nph.com/1/new.html,会跳转www.nph.com

nginx 支持 tcp dubbo nginx 支持patch_html_27