Nginx的rewrite和location

224 阅读3分钟

rewrite简介

rewrite跳转场景

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

rewrite跳转实现过程

20210407155215243.png

rewrite实际场景

  • Nginx跳转需求的实现方式

    使用rewrite进行匹配跳转

    使用if匹配全局变量后跳转

    使用location匹配再跳转

  • rewrite放在server{},if{},location{}段中

    location只对域名后边的除去传递参数外的字符串起作用

  • 对域名或参数字符串

    使用if全局变量匹配

    使用proxy_pass反向代理

nginx正则表达式

常用正则表达式元字符

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

rewrite命令

rewrite 命令语法

rewrite  <正则表达式>  <跳转后的内容>  [rewrite支持的flag标记]

flag标记说明

名称含义
last本条规则匹配完成后,不终止重写后的url匹配,一般用在 server 和 if 中。
break本条规则匹配完成即终止,终止重写后的url匹配,一般使用在 location 中。
redirect返回302临时重定向,浏览器地址会显示跳转后的URL地址。
permanent返回301永久重定向,浏览器地址栏会显示跳转后的URL地址

last与break比较

  1. last:url重写后,马上发起一个新请求。再次进入server块,重试location匹配,超过10次匹配不到报500错误,地址栏不变。
  2. break:url重写后,直接使用当前资源,不再使用location余下的语句,完成本次请求,地址栏不变。

总结:last和break在重定向后,地址栏都不会发生变化,这是它们的相同点,不同点在于last会写在server和if中,break是写在location中,last不会终止重写后的url匹配,break会终止重写后的url匹配。

location

location 常用的匹配规则

= :进行普通字符精确匹配,也就是完全匹配。
^~ :表示普通字符匹配。使用前缀匹配。如果匹配成功,则不再匹配其它 location。
~ :区分大小写的匹配。
~* :不区分大小写的匹配。
!~ :区分大小写的匹配取非。
!~* :不区分大小写的匹配取非。

location 优先级

1、相同类型的表达式,字符串长的会优先匹配
2、按优先级排列(把最先执行的写在配置文件的最上面)
= 类型
^~ 类型表达式
正则表达式(和*)类型
常规字符串匹配类型,按前缀匹配
通用匹配(/),如果没有其它匹配,任何请求都会匹配到

rewrite与location比较

  1. 相同点:

    都能实现跳转

  2. 不同点:

    rewrite是在同一域名内更改获取资源的路径

    location是对一类路径做控制访问或反向代理,还可以 proxy_pass到其他机器

  3. rewrite会写在location里,执行顺序

    执行server块里面的rewrite指令

    执行location匹配

    执行选定的location中的rewrite指令

location优先级示例

location = / {	###精确匹配 /,主机名后面不能带任何字符串
    [configuraion A ]	
}

location / {	###所有的地址都以/开头,这条规则将匹配到所有请求,但正则和最长字符串会优先匹配
    [configuraion B ]
}

location /documents/ {		###匹配任何以/documents/开头的地址,当后面的正则表达式没有匹配到时,才起作用
    [configuraion C ]
}

location ~ /documents/abc {		###匹配任何以/documents/abc开头的地址,当后面的正则表达式没有匹配到时,才会起作用
    [configuraion D ]
}

location ^~ /images/ {	###以/images/开头的地址,匹配符合后,停止往下匹配
    [configuraion E ]
}

location ~*\.(gif|jpg|gpeg)$ {	###匹配所有以 gif, jpg或jpeg结尾的请求, Images/下的图片会被 [configuration E]处理,因为^~的优先级更高
    [configuraion F ]
}

location /images/abc {	###最长字符匹配到 /images/abc,优先级最低
    [configuraion G ]
}

location ~ /images/abc {	###以/ Images/abc开头的,优先级次之
    [configuraion H ]
}

location /images/abc/1.html {	###如果和正则 ~ images/abc/1.htm相比,正则优先级更高
    [configuraion I ]
}

location常用优先级规则

  1. 匹配某个具体文件
location = 完整路径)>(location ^~ 完整路径)>(location ~* 完整路径)=(location ~ 完整路径)>(location 目录)>(location /)
  1. 用目录做匹配访问整个文件
location = 目录)>(location ^~ 目录)>(location ~* 目录)=(location ~ 目录)>(localtion 目录)>(location /)

实用案例

环境:需安装nginx服务

基于域名的跳转

现在公司旧域名www.old.com有业务需求有变更,需要使用新域名www.new.com代替。
要求:
旧域名不能废除,需要跳转到新域名上,而且后面的参数保持不变

修改配置文件

[root@client1 ~]# ln -s /usr/local/nginx/conf/nginx.conf /etc/nginx.conf
[root@client1 ~]# vi /etc/nginx.conf
......
    server {
        listen       80;
        server_name  www.old.com;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
            if ($host = 'www.old.com')  #rewrite的配置
               {
         rewrite ^/(.*)$ http://www.new.com/$1 permanent;    #将旧域名重写为新域名
               }
        }
......
#重启服务,可能需要重启电脑
systemctl restart nginx

添加映射

vi /etc/hosts
192.168.235.10 www.old.com www.new.com

验证,访问www.old.com,域名会自动跳转成新域名

20210407160425398.png

基于新旧域名跳转并加目录

将域名old.aa.com下面的发帖都跳转到http://www.bb.com…

修改配置文件

[root@client1 ~]# vi /etc/nginx.conf 
    server {
        listen       80;
        server_name  old.aa.com;    
        #charset koi8-r;    
        #access_log  logs/host.access.log  main;
                  
        location  /post {    #访问post路径下的网页,会跳转到,www.bb.com/bbs,下对应的网页
             rewrite (.+) http://www.bb.com/bbs$1 permanent;
        }
  
        location / {
            root   html;
            index  index.html index.htm;
            .....   
#重启服务
systemctl restart nginx

创建bbs目录

[root@client1 ~]# cd /usr/local/nginx/html/
[root@client1 html]# mkdir -p bbs/post
[root@client1 html]# cd bbs/post/
[root@client1 post]# vi index.html
welcom new web

添加IP与主机的映射,用哪个主机访问,就要在哪个主机上添加映射

[root@client1 post]# vi /etc/hosts
192.168.235.10 old.aa.com www.bb.com

测试。访问old.aa.com/post/index.html,,会跳转成如下页面

2021040716103954.png

基于参数匹配的跳转

访问www.bb.com/100-(100|20…

跳转到wwwbb.com页面。\

修改配置文件

[root@client1 post]# vi /etc/nginx.conf 

    server {
        listen       80;
        server_name  www.bb.com;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        #如果访问的域名跟上100-100-数字或100-200-数字.html的形式结尾,则跳转
        if ($request_uri ~ ^/100-(100|200)-(\d+).html$) {
            rewrite (.*) http://www.bb.com permanent;
        }

        location / {
            root   /usr/local/nginx/html;
            index  index.html index.htm;
......
#重启服务
systemctl restart nginx

测试,访问www.bb.com/100-200-13.html,或www.bb.com/100-100-99.html

20210407161344657.png

基于客户端ip访问跳转

要求:
公司内部可以用来访问服务器的地址为192.168.35.10,其他客户端访问时跳转到error网页提示网页在维护,不可用
修改配置文件

[root@client1 ~]# vi /etc/nginx.conf 
    #gzip  on;   
    server {
        listen       80;
        server_name  www.aa.com;  #设置域名
        
        set $rewrite true;
            if ($remote_addr = "192.168.235.10"){   #仅本服务器访问时可访问正常页面
                 set $rewrite false;
            }
            
            if ($rewrite = true){   #其余客户机访问时,跳转到error网页
                 rewrite (.+) /error.html;
            }
            
            location = /error.html {
            root /usr/local/nginx/html;  #error网页目录
            }
            
            location / {
            root   html;
            index  index.html index.htm;
            ......

重启服务并关闭防火墙

systemctl restart nginx
systemctl stop firewalld
setenforce 0

添加映射

vi /etc/hosts
192.168.235.10 www.aa.com

其他客户机打开显示维护

20210407160744936.jpg

基于目录下所有PHP文件的跳转

访问wwwbb.com/upload/test…

修改配置文件

[root@client1 post]# vi /etc/nginx.conf
 server {
        listen       80;
        server_name  www.bb.com;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location ~* /upload/.*\.php$ {   #访问upload/目录下所有的PHP结尾的网页时跳转,不区分大小写
            rewrite (.+) http://www.bb.com permanent;
        }
        location  / {
            root   html;
            index  index.html index.htm;
        }
        ......
#重启服务
systemctl restart nginx

20210407161417711.png

基于最普通url请求的跳转

访问一个具体的页面跳转到首页,如浏览器访问www.bbcom/test/test.h… 修改配置文件

[root@client1 post]# vi /etc/nginx.conf
 server {
        listen       80;
        server_name  www.bb.com;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location ~* ^/test/test.html {
          rewrite (.+) http://www.bb.com permanent;
        }
        location  / {
            root   html;
            index  index.html index.htm;
        }
        ......
#重启服务
systemctl restart nginx


20210407161452274.png