nginx 中 alias 如果使用正则匹配导致多次301问题

前端项目有个需求,在匹配路径诸如:https://www.xxxx.com/dev/sample/0.1/3232/imt/的时候访问前端vue项目ote: for curly braces( { and } ), as they are used both in regexes and for block...

前端项目有个需求,在匹配路径诸如:https://www.xxxx.com/dev/sample/0.1/3232/imt/的时候访问前端vue项目


其中标黄的数字部分,是可以变化的,规则是:只要满足4四位以上的数字就可以正常显示页面。


这其中遇到两个问题:


1,匹配的路径比较长,如果使用nginx 的location root指定访问路径,真实路径匹配问题比较麻烦,需要多次rewrite才可以,

使用alias的时候,普通匹配没有问题,如果使用alias的正则匹配,会出现多次重定向导致访问出错。


2,在使用正则的时候,location 匹配时候出现 '{}' 时候,nginx会报错,这应该是和后面的指令块的“大括号”有歧义。


经过查询文档,对于对一个问题发现,alias使用正则匹配的时候,需要正则捕获,并且捕获到的分组要应用到alias上。


nginx中如下配置解决问题:



location ~* "^/dev/sample/0.1/\d{4,}/imt/(.*)$" {

       alias /webdata/webdir/website/wp-content/uploads/2019/11/$1;

       index index.html index.htm index.php;

   }



alias path;
location

Defines a replacement for the specified location. For example, with the following configuration

location /i/ {
    alias /data/w3/images/;
}

on request of “/i/top.gif”, the file /data/w3/images/top.gif will be sent.

The path value can contain variables, except $document_root and $realpath_root.

If alias is used inside a location defined with a regular expression then such regular expression should contain captures and alias should refer to these captures (0.7.40), for example:

location ~ ^/users/(.+\.(?:gif|jpe?g|png))$ {
    alias /data/w3/images/$1;
}

When location matches the last part of the directive’s value:

location /images/ {
    alias /data/w3/images/;
}

it is better to use the root directive instead:

location /images/ {
    root /data/w3;
}


对于第二个问题:

因为nginx的location正则匹配中 出现 “大括号{}” 为非法,所有只要在正则表达式上加上双引号(单引号也是可以的) 就可以解决问题了


qote: for curly braces( { and } ), as they are used both in regexes and for block control, to avoid conflicts, regexes with curly braces are to be enclosed with double quotes (or single quotes).

  • 发表于 2021-09-21 23:38
  • 阅读 ( 43 )

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
shitian
shitian

662 篇文章

作家榜 »

  1. shitian 662 文章
  2. 石天 437 文章
  3. 每天惠23 33 文章
  4. 小A 29 文章