简体   繁体   中英

How to write regular expression in Nginx location default file to map port to proxy_pass?

I had gone through too many answers on stackoverflow but not able to figure it out how to write regex for my requirement.
Here my http://server/xyz/1234/1233/8080/ I have used the following regex location to redirect the above http://server/xyz/1234/1233/8080/ to 127.0.0.1:8080, but it is giving me 404 Not Found Error.

I am writing this location block in default file.

 location ~ ^/xyz/([0-9]+)/([0-9]+)/([0-9]+)/
 {
    rewrite ^/xyz/([0-9]+)/([0-9]+)/(.*)/$ break;
    proxy_pass http://localhost:$1;
    proxy_set_header Host $host;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection upgrade;
 }

I don't know where I am making wrong because I have used it like as said

  • ^, $ - Represents start and end of line respectively.

  • (.*) - Represents first capturing group matching everything.

You have three capturing groups in your rewrite directive:

^/xyz/([0-9]+)/([0-9]+)/(.*)/$
      ↑        ↑        ↑
      first    second   third

but you trying to use first group as upstream port. Anyway, you don't need any rewrite rule here. You can just declare named group in location and use match as nginx variable, like this:

location ~ ^/xyz/([0-9]+)/([0-9]+)/(?<my_port>[0-9]+)/$ {
    proxy_pass http://localhost:$my_port;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM