Search code examples
regexnginxhttp-proxy

Nginx location regex capture variable


I have this REST API URL:

http://localhost:4000/api/v2/stocks/accounts/1162/tradings

I want it to proxy_pass to URL:

http://localhost:4001/api/v2/stocks/accounts/1162/tradings

Where 1162 is the URL parameter which can be other value.

I have the following:

location ^~ /api/v2/stocks/accounts/([^/]+)/tradings {
      proxy_pass http://localhost:4001/api/v2/stocks/accounts/$1/tradings;
}

But it doesn't work (404 Not Found), I have googled similar problem, but not much help:

Like this one: Get arguments Nginx and path for proxy_pass or this one: trouble with location regex and redirection in nginx.

Is there any way to achieve what I want, using nginx?

Thanks in advance for any help.

ADDED:

I also added parameters capture:

location ~ /api/v2/stocks/accounts/([^/]+)/tradings/(.*) {
    proxy_pass http://localhost:4001/api/v2/stocks/accounts/$1/tradings/$2$is_args$args;
}

Solution

  • You can do it just like this. NOT '^~'

    location ~ /api/v2/stocks/accounts/([^/]+)/tradings {
      proxy_pass http://localhost:4001/api/v2/stocks/accounts/$1/tradings;
    }
    

    As described by nginx.org.
    The ^~ is often to match directory, like this below:

    location ^~ /dir/ {
        # some actions
    }