Nginx Rewrit的跳转

Nginx rewrite跳转
现在 Nginx 已经成为很多公司作为前端反向代理(proxy_pass)服务器的首选,在工作中往往会遇到很多跳转(重写 URL)的需求。
比如:更换域名后需要保持旧的域名能跳转到新的域名上、某网页发生改变需要跳转到新的页面、网站防盗链等等需求。如果在后端使用的 Apache 服务器,虽然也能做跳转,规则库也很强大,但是用 Nginx 跳转效率会更高(正则精确匹配)。

Nginx跳转需求的实现方式
①使用rewrite进行匹配跳转(主要匹配的是具体的路径)
②使用if匹配全局变量后跳转
③使用location匹配再跳转(可以匹配后执行proxy_pass,将请求跳转到其他服务上)

##常用的 Nginx 正则表达式
使用正则表达式的好处
①精确匹配,减少遍历的消耗
②节省服务响应的资源消耗
③提高用户体验感
④提高服务器高并发时处理效率/性能)

常用的正则表达式元字符
^ :匹配输入字符串的起始位置
$ :匹配输入字符串的结束位置

  • :匹配前面的字符零次或多次。如“ol*”能匹配“o”及“ol”、“oll”
  • :匹配前面的字符一次或多次。如“ol+”能匹配“ol”及“oll”、“olll”,但不能匹配“o”
    ? :匹配前面的字符零次或一次,例如“do(es)?”能匹配“do”或者“does”,”?”等效于”{0,1}”
    . :匹配除“\n”之外的任何单个字符,若要匹配包括“\n”在内的任意字符,请使用诸如“[.\n]”之类的模式
    \ :将后面接着的字符标记为一个特殊字符或一个原义字符或一个向后引用。如“\n”匹配一个换行符,而“$”则匹配“$”
    \d :匹配纯数字
    \w :匹配字母或数字或下划线或汉字
    \s :匹配任意的空白符
    \b :匹配单词的开始或结束
    {n} :重复 n 次
    {n,} :重复 n 次或更多次
    {n,m} :重复 n 到 m 次
    [] :定义匹配的字符范围
    [c] :匹配单个字符 c
    [a-z] :匹配 a-z 小写字母的任意一个
    [a-zA-Z0-9] :匹配所有大小写字母或数字
    () :表达式的开始和结束位置 例如:(jpg|gif|swf|)
    | :或运算符

从功能看 rewrite 和 location 似乎有点像,都能实现跳转,主要区别在于 rewrite 是在同一域,location 是对一类路径做控制访问或反向代理,还可以 proxy_pass 到其他机器。

###############################Rewrite#####
一、Rewrite跳转场景
1、调整用户浏览的URL,看起来更规范,合乎开发及产品人员的需求。
2、为了让搜索引擎搜寻网站内容及用户体验更好,企业会将动态URL地址伪装成静态地址提供服务。
3、网址换新域名后,让旧的访问跳转到新的域名上。例如,访问京东的 360buy.com 会跳转到 jd.com。
4、服务端某些业务调整,比如根据特殊变量、目录、客户端的信息进行URL调整等。
URL 匹配和 重新跳转新的URL
nginx rewrite(RUL)

二、Rewrite 跳转实现
Nginx:通过ngx_http_rewrite_module 模块支持URL重写、支持if条件判断,但不支持else
跳转:从一个location跳转到另一个location, 循环最多可以执行10次,超过后nginx将返回500错误
PCRE支持:perl兼容正则表达式的语法规则匹配
重写模块 set 指令:创建新的变量并设其值

三、rewrite功能
rewrite功能就是,使用nginx提供的全局变量或自己设置的变量,结合正则表达式和标记位实现URL重写以及重定向。
比如:更换域名后需要保持旧的域名能跳转到新的域名上、某网页发生改变需要跳转到新的页面、网站防盗链等等需求。

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

对域名或参数字符串
使用if全局变量匹配
使用proxy_pass反向代理
例如 http://www.dabao.com/a/we/index.php?id=1&u=str 只对/a/we/index.php重写。

四、rewrite 执行顺序如下:
(1) 执行 server 模块里面的rewrite 指令。
(2) 执行选定的 location 中的rewrite 指令。
(3) 执行选定的location中 if 中的rewrite指令
示例:
http {

server {
rewrite # 优先级1
location ~*.(jpg|gif|swf)$ {
rewrite # 优先级2
valid_referers none blocked *.dog.com dog.com;
if ( $invalid_referer ) {
rewrite ^/ http://www.dog.com/error.png; #优先级3
}
}
}
}

www.dog.com/rabbit.jpg
rewrite ^/ http://www.dog.com/error.png;

^/ : 以^/,匹配到/rabbit.jpg

location / { }

五、语法: rewrite ;
rewrite [flag];
regex:表示正则匹配规则。
replacement:表示跳转后的内容。
flag:表示 rewrite 支持的 flag 标记。

####flag标记说明
last:本条规则匹配完成后,继续向下匹配新的location URL规则,一般用在server和 if 中。
break:本条规则匹配完成即终止,不再匹配后面的任何规则,一般使用在location中。
redirect:返回302临时重定向,浏览器地址会显示跳转后的URL地址。
permanent:返回301永久重定向,浏览器地址栏会显示跳转后的URL地址。

注:last和break最大的不同在于

  • break 是终止当前location的rewrite检测,而且不再进行location匹配
  • last 是终止当前location的rewrite检测,但会继续重试location匹配并处理区块中的rewrite规则

c:/windows/system32/drivers/etc

location
一、location 大致可以分为三类:
精准匹配:location = / {…} 示例: location = patt {} PS: 精确匹配字符串
一般匹配:location / {…} 示例: location patt {} PS: 只要包含patt的字符串即可
正则匹配:location ~ / {…} 示例: location ~ patt {} PS: 按照正则表达式的方式匹配

二、location 常用的匹配规则:
=:进行普通字符精确匹配,也就是完全匹配
^~:表示普通字符匹配。使用前缀匹配。如果匹配成功,则不再匹配其他 location
~:区分大小写的匹配
~:不区分大小写的匹配
!~:区分大小写的匹配取非
!~
:不区分大小写的匹配取非
@:定义一个location,使用在内部定向的时候

三、location 优先级:
相同类型的表达式,字符串长的优先匹配

按优先级排列
精确匹配 :=类型
前缀匹配普通字符: ^~类型表达式
是按文件中顺序的正则匹配: * 正则表达式类型
常规字符串匹配类型,按前缀,示例:/images/abc/ location /patt
通用匹配 (/),没有其他匹配,任何请求都将匹配

rewrite和location的比较
相同点
都能实现跳转
①rewrite改写访问的URL路径〔被访问的HTML/HTM/CSS文件)
②location对一类地址进行权限控制(认证控制)+跳转(跨服务器进行URL跳转)

不同点
rewrite是在同一域名内更改获取资源的路径
location时对一类路径做控制访问或反向代理,还可以proxy_pass到其他机器
rewrite会写在location里,执行顺序
执行server块里面的rewrite指令
执行location匹配
执行选定的location中的rewrite指令

四、location 示例说明

www.baidu.com/data

1、location = / {}
= 为精确匹配 /,主机名后面不能带任何字符串,比如访问 / 和 /data,则 / 匹配,/data 不匹配
再比如 location = /abc,则只匹配 /abc,/abc/或 /abcd不匹配。若 location /abc ,则即匹配/abc、/abcd/ 同时也匹配/abc/。

2、location / {} www.kgc.com/路径
因为所有的地址都以/开头,所以这条规则将匹配到所有请求比如访问/和/data, 则/匹配,/data 也匹配,
但若后面是正则表达式会和最长字符串优先匹配(最长匹配)

3、location /documents/ {}
匹配任何以/documents/ 开头的地址,匹配符合以后,还要继续往下搜索其它location
只有其它location后面的正则表达式没有匹配到时,才会采用这一条
www.kgc.com/documents
www.kgc.com/documents/index

4、location /documents/abc {}
匹配任何以/documents/abc 开头的地址,匹配符合以后,还要继续往下搜索其它location
只有其它location后面的正则表达式没有匹配到时,才会采用这一条

5、location ^~ /images/ {}
location ^~ /abcdef/
匹配任何以/images/ 开头的地址,匹配符合以后,停止往下搜索正则,采用这一条

6、location ~* . (gif|jpg|jpeg)$ {}
匹配所有以gif、jpg或jpeg结尾的请求
然而,所有请求/images/下的图片会被location ^~ /images/ 处理,因为^~的优先级更高,所以到达不了这一条正则

7、location /images/abc {}
最长字符匹配到/images/abc,优先级最低,继续往下搜索其它location, 会发现^存在

8、location ~ /images/abc {}
匹配以/images/abc开头的,优先级次之,只有去掉location ^~ /images/ 才会采用这一条

9、location /images/abc/1.html {}
匹配/images/abc/1.html文件,如果和正则location ~ /images/abc/1.html相比,正则优先级更高

优先级总结(面试题,location 优先级是怎么排列的):
匹配某个具体文件
(location = 完整路径) > (location ^~ 完整路径) > (location ~* 完整路径) > (location ~ 完整路径) > (location 完整路径) > (location /)

location ~ Abc {}
location ~ abc {}

location ~* abc {}

用目录做匹配访问某个文件
(location = 目录) > (location ^~ 目录/) > (location ~ 目录) > (location ~* 目录) > (location 目录) > (location /)

文件 目录 为什么只会在区不区分大小写上会有变动
正则表达式:目的是为了尽量精确的匹配
文件——》尽量精确匹配,区分大小写 精确、不区分更为精确
目录——》尽量精确匹配,区分大小写 精确 优先级更高,不区分大小写的

/abc 目录 test01
/Abc 目录 没有
分别有100个文件

location ~ /abc {
test01.txt
}

location ~ /Abc {
test01.txt
}

五、实际网站使用中,至少有三个匹配规则定义:

#第一个必选规则
直接匹配网站根,通过域名访问网站首页比较频繁(www.baidu.com/),使用这个会加速处理,比如说官网。
可以是一“个静态首页,也可以直接转发给后端“应用服务器” ——》PHP 、Apache
location = / {
root html;
index index.html index. htm;
}

#第二个必选规则是处理静态文件请求,这是nginx作为http服务器的强项(1、静态请求处理的能力+ 高并发处理能力+资源消耗较低)
有两种配置模式,目录匹配或后缀匹配,任选其一或搭配使用
location ^~ /static/ {
root /webroot/static/ ;
}

location ~* . (html Igif ljpg ljpeglpnglcssljslico)$ {
root /webroot/res/ ;
}

用规则,比如用来转发带.php、.jsp后缀的动态请求到后端应用服务器
非静态文件请求就默认是动态请求(跳转/反向代理)
upstream tomcat_server {
server 192.168.226.128:8080 weight 1;
server 192.168.226.132:8080 weight 1;
}

location ^/ .(php|jsp)$ {
proxy_pass http://tomcat_server;
}

###################工作场景#######

一、基于域名的跳转
现在公司旧域名www.kgc.com有业务需求变更,需要使用新域名www.benet.com代替,但是旧域名不能废除,需要跳转到新域名上,而且后面的参数保持不变。
#添加映射
vim /etc/hosts
192.168.226.132 www.benet.com www.kgc.com
在这里插入图片描述

#创建日志目录
mkdir -p /var/log/nginx/

#修改配置文件
vim /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name www.kgc.com; #域名修改

    #charset koi8-r;

    access_log  /var/log/nginx/www.kgc.com-access.log;     #开启并对日志保存路径进行修改

    location / {											#在原有location 位置插入
         if ($host = 'www.kgc.com'){       	#$host为rewrite全局变量,代表请求主机头字段或主机名
            rewrite ^/(.*)$ http://www.benet.com/$1 permanent;   #$1为匹配的位置变量,即域名后边得字符串,同时永久跳转
        }
        root   html;
        index  index.html index.htm;
    }

在这里插入图片描述

systemctl restart nginx.service

www.baidu.com

此时访问 http://www.kgc.com 时会自动跳转到 www.benet.com 上进行访问。
同时,可以访问http://www.kgc.com/1.html 在显示错误页面的同时可以看到域名也会变化为www.benet.com/1.html
在这里插入图片描述

因为$1 标志位,而标志位的含义包含了 ① 标记的对象URL ② 标记的具体部分,而标记的具体部分是用$0和$1来表示的
完整的URL : http://www.kgc.com/1.html
$0:http://www.kgc.com
$1:/1.html
标志位:标记什么位:标记的具体部分 $0 $1

二、基于客户端 IP 访问跳转

今天公司业务新版本上线,要求所有 IP 访问任何内容都显示一个固定维护页面,只有公司 IP 192.168.10.31访问正常。
① 删除上一个实验的配置

vim /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name www.kgc.com;

    #charset koi8-r;

    access_log  /var/log/nginx/www.kgc.com-access.log;

#设置是否是合法的IP标记
set KaTeX parse error: Expected 'EOF', got '#' at position 19: …rite true; #̲设置变量rewrite,变量形式为布尔值为true
#判断是否为合法IP
if ($remote_addr = “192.168.226.128”){ #当客户端IP为192.168.226.132时,将变量值设为flase,不进行重写
set KaTeX parse error: Expected 'EOF', got '}' at position 24: …false; }̲ #除了合法IP,其它都是非法…rewrite = true){ #布尔值表达式在不满足false情况下,会匹配满足true的location
rewrite (.+) /weihu.html; #重写在访问IP后边插入/weihu.html,例如192.168.226.160/weihu.html
}
location = /weihu.html {
root /var/www/html; #页面返回/var/www/html/weihu.html的内容
}
location / {
root html;
index index.html index.htm;
}

复制:
set r e w r i t e t r u e ; i f ( rewrite true; if ( rewritetrue;if(remote_addr = ‘192.168.226.132’) {
set KaTeX parse error: Expected 'EOF', got '}' at position 23: … false; }̲ if (rewrite = true) {
rewrite (.+) /weihu.html;
}
location = /weihu.html {
root /var/www/html;
}

在这里插入图片描述

mkdir -p /var/www/html
echo ‘

this is weihu web!

’ > /var/www/html/weihu.html
systemctl restart nginx.service

此时用另外一台机子访问192.168.226.132时会跳转到weihu.html界面,而只有IP为192.168.226.132的机子才可以正常进行访问。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

三、基于旧域名跳转到新域名后面加目录
当访问的是 http://bbs.pxs.com/post/1.html 会自动跳转到 http://www.benet.com/bbs/post/1.html

http://bbs.pxs.com/post/1.html

#创建指定目录
[root@localhost ~]# mkdir -p /usr/local/nginx/html/bbs/post
[root@localhost ~]# echo "

this is 1.html

" >> /usr/local/nginx/html/bbs/post/1.html
[root@localhost ~]# echo “192.168.226.132 bbs.pxs.com” >> /etc/hosts

vim /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name bbs.pxs.com; #修改域名

    #charset koi8-r;

    access_log  /var/log/nginx/www.benet.com-access.log;		#修改日志名

    #添加 ,旧:bbs.pxs.com/post/i.html
    location /post {
      rewrite (.+) http://www.benet.com/bbs$1 permanent;    #这里$1为位置变量,代表/post
    }
    location / {
        root   html;
        index  index.html index.htm;
    }

在这里插入图片描述

#重启服务
[root@localhost ~]#systemctl stop nginx.service
[root@localhost ~]#systemctl start nginx.service

此时用浏览器访问 http://bbs.pxs.com/post/1.html 会自动跳转到 http://www.benet.com/bbs/post/1.html

#旧
http://bbs.kgc.com/post/1.html


http://www.benet.com/bbs/post/1.html
在这里插入图片描述

四、基于参数匹配(多余的)的跳转

现在访问 http://www.pxs.com/100-(100|200)-100.html 会跳转到 http://www.pxs.com的页面

vim /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name www.pxs.com; #修改域名

    #charset koi8-r;

    access_log  /var/log/nginx/www.pxs.com-access.log;		#日志

#KaTeX parse error: Undefined control sequence: \d at position 24: …uri 内置变量,表示URI,\̲d̲ ̲纯数字 if …request_uri ~ ^/100-(100|200)-(\d+).html$){ #设置正则匹配,示例:http://www.pxs.com/100-100-1231.html
rewrite (.*) http://www.pxs.com permanent; #设置重写
}
location / {
root html;
index index.html index.htm;
}
在这里插入图片描述

systemctl restart nginx.service

使用浏览器访问 http://www.pxs.com/100-100-100.html 或 http://www.pxs.com/100-200-100.html会自动跳转到 http://www.pxs.com页面

五、基于目录下所有 php 结尾的文件跳转

要求访问 http://www.pxs.com/upload/123.php 跳转到首页www.pxs.com (场景:注册/登陆)

vim /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name www.pxs.com

    #charset koi8-r;

    access_log  /var/log/nginx/www.pxs.com-access.log;

    location ~* /upload/.*\.php$ {					#什么含义?
       rewrite (.+) http://www.pxs.com permanent;
    }

    location / {
        root   html;
        index  index.html index.htm;
    }

systemctl restart nginx.service

在这里插入图片描述

浏览器访问 http://www.pxs.com/upload/123.php 跳转到 http://www.pxs.com 首页

六、基于最普通一条 url 请求的跳转

要求访问一个具体的页面,如: http://www.pxs.com/abc/123.html到首页

vim /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name www.kgc.com;

    #charset koi8-r;

    access_log  /var/log/nginx/www.pxs.com-access.log;

    location ~* /abc/123.html {
       rewrite (.+) http://www.pxs.com permanent;
    }

    location / {
        root   html;
        index  index.html index.htm;
    }

systemctl restart nginx.service
在这里插入图片描述
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值