非贪婪的nginx位置正则表达式返回404错误

时间:2014-12-17 18:52:07

标签: regex nginx pcre

我想配置一个nginx location directive,它会重定向以下网址:

/api/v2/<map_id>/region

要:

http://SOME-URL/api/v2/<map_id>/region

map_id是任何不包含/的字符串。

我试过了:

location /api/v2/((?U).*)/region {
    proxy_pass http://SOME-URL/api/v2/$1/region;
}

但我仍然收到404错误。我还尝试用$1替换$2,但没有运气。

如何修复此正则表达式的任何想法?

更新 - 修复了地区/地区的差异。

2 个答案:

答案 0 :(得分:4)

单个~是所有痛苦的根源:

  

In order to use regular expressions, you must always use a prefix:

     

“〜”必须用于区分大小写的匹配

     

“〜*”必须用于不区分大小写的匹配

所以:

location ~ /api/v2/([^/]*)/region {
    proxy_pass http://SOME-URL/api/v2/$1/region;
}

诀窍 - ?U部分甚至没有必要。

/var/log/nginx/error.log的错误日志提供了一个有用的线索:

2014/12/21 12:54:59 [emerg] 7506#0: invalid URL prefix in /etc/nginx/sites-enabled/super_secret_filename_dont_share_on_so.conf:42

答案 1 :(得分:1)

首先,您在regionregions之间存在差异。那肯定会这样做。

其次,您可以使用这样的否定字符类:

/api/v2/([^/]*)/region

你可能也需要在那里逃避一些斜线,虽然我并不完全确定Nginx需要什么。

在任何PCRE正则表达式中,您都需要执行以下操作:

\/api\/v2\/([^\/]*)\/region

这里正在研究regex101:https://regex101.com/r/mT3xB9/1

相关问题