英文:
Regex in nginx config location
问题
以下是为此nginx配置编写正则表达式的正确方法:
location ~ /handler1/(?<var1>.*) {
proxy_pass http://www.test.com/handler1/$var1;
}
location ~ /handler1/(?<var1>.*)/handler2 {
proxy_pass http://www.test.com/handler1/$var1/handler2;
}
location ~ /handler1/(?<var1>.*)/handler2/(?<var2>.*)/handler3 {
proxy_pass http://www.test.com/handler1/$var1/handler2/$var2/handler3;
}
请使用上述正则表达式来匹配您的nginx配置。希望这对您有所帮助!
英文:
Help how to correctly compose a regex for this nginx configuration
location ~ /handler1/(?<var1>.*) {
proxy_pass http://www.test.com/handler1/$var1;
}
location ~ /handler1/(?<var1>.*)/handler2 {
proxy_pass http://www.test.com/handler1/$var1/handler2;
}
location ~ /handler1/(?<var1>.*)/handler2/(?<var2>.*)/handler3 {
proxy_pass http://www.test.com/handler1/$var1/handler2/$var2/handler3;
}
I tried different options but always hit the first match
I use this service https://nginx.viraptor.info/ to check the config
result
答案1
得分: 0
以下是翻译好的内容:
问题在于 /handler1/(?<var1>.*)
会匹配包含 /handler1/
的任何内容,所以在你的示例中,var1 将是 asd2/handler2
。你需要反转位置正则表达式,以便更具体的位置首先匹配。所以这将起作用:
server {
listen 80;
server_name domain2.com www.domain2.com;
access_log logs/domain2.access.log main;
location ~ /handler1/(?<var1>.*)/handler2/(?<var2>.*)/handler3 {
proxy_pass http://www.test.com/handler1/$var1/handler2/$var2/handler3;
}
location ~ /handler1/(?<var1>.*)/handler2 {
proxy_pass http://www.test.com/handler1/$var1/handler2;
}
location ~ /handler1/(?<var1>.*) {
proxy_pass http://www.test.com/handler1/$var1;
}
}
秘诀是:
https://www.digitalocean.com/community/tutorials/nginx-location-directive
为了找到URI的位置匹配,NGINX首先扫描使用前缀字符串(不使用正则表达式)定义的位置。然后,按照在配置文件中声明的顺序检查具有正则表达式的位置。
英文:
The problem is that /handler1/(?<var1>.*)
will match ANYTHING that contains /handler1/
so var1 will be asd2/handler2
in your example. You need to reverse the location regexes so the more specific ones come first. So this will work:
server {
listen 80;
server_name domain2.com www.domain2.com;
access_log logs/domain2.access.log main;
location ~ /handler1/(?<var1>.*)/handler2/(?<var2>.*)/handler3 {
proxy_pass http://www.test.com/handler1/$var1/handler2/$var2/handler3;
}
location ~ /handler1/(?<var1>.*)/handler2 {
proxy_pass http://www.test.com/handler1/$var1/handler2;
}
location ~ /handler1/(?<var1>.*) {
proxy_pass http://www.test.com/handler1/$var1;
}
}
The secret is:
https://www.digitalocean.com/community/tutorials/nginx-location-directive
>To find a location match for an URI, NGINX first scans the locations that is defined using the prefix strings (without regular expression). Thereafter, the location with regular expressions are checked in order of their declaration in the configuration file.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论