'Nginx regex location not matching
I am serving some services on an Ubuntu VM using Nginx 1.14.0. In my server definition, I'm including a location block designed to forward requests from /api/v{version}/users{suffix} where version is supposed to be a number like 1.0 or 2.1 and suffix can be empty or could be part of the route. My goal is to forward to localhost:5006/v{version}/users{suffix}. The reason I'm doing things this way is that I also have /api/v{version}/rooms{suffix} and /api/v{version}/prompts{suffix} and these go to separate ports. Currently, my location block looks like this:
location ~ ^\/api\/v(([0-9]+)\.([0-9]+))\/users(.*)$ {
proxy_pass https://localhost:5006/v$1/users$2;
proxy_http_version 1.1;
proxy_pass_request_headers on;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
However, when I try to call /api/v1.0/users/31245 I get a 502 and, on inspection of my error logs, I see this:
[error] 2591#2591: *6052 no resolver defined to resolve localhost, client: [MY_IP_ADDR], server: [SERVER_NAME], request: "GET /api/v1.0/users/158015ab-3811-4137-8a13-102d9b400050 HTTP/1.1"
This appears to be happening because the request couldn't be matched to a location. I've tested this on several different Nginx testers and it seems to work so what am I doing wrong here?
Solution 1:[1]
Using variables within the proxy_pass statement requires Nginx to use a resolver. See this document for details.
Either specify a resolver statement, or better still, rewrite the block to avoid using variables in the proxy_pass statement.
For example:
location ~ ^/api/v[0-9]+\.[0-9]+/users {
rewrite ^/api(.*)$ $1 break;
proxy_pass https://localhost:5006;
...
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Richard Smith |
