Search code examples
regexnginxhttp-redirectproxyload-balancing

NGinx location directive with Regex


I'm looking for a way to get my NGinx LB to do the following conversion.

  • User access URL: https://example.com/t/foo.com/common/<something>
  • Proxied by LB: https://example.com/<something>?t=foo.com

First of all, is this possible to be done?

I tried the below config but didn't work as expected.

server {
    listen 443;
    server_name example.com;
    ssl on;
    ssl_certificate /etc/ssl/certs/example-selfsigned.crt;
    ssl_certificate_key /etc/ssl/private/example-selfsigned.key;
    
    location /t/[a-z.]+/common/ {

        rewrite ^(/t/.*)/common/(.*)$ https://192.168.1.3:9443/$2?t=$1 break;

        proxy_pass https://192.168.1.3:9443/;

    }
}

Any help on this would be greatly appreciated!


Solution

  • Regex matching locations should use ~ (or ~* for case-insensitive matching) modifiers. You should not add the scheme or domain part to your rewrite directive when you want to rewrite an URI that to be proxied with proxy_pass directive. Try the following:

    location ~ ^/t/(?<t>[a-z.]+)/common(?<path>/.*) {
        rewrite ^ $path?t=$t break;
        proxy_pass proxy_pass https://192.168.1.3:9443;
    }