Reputation: 87
Hi i want to set a dynamic proxy pass in nginx. $myvar will take values such as ops/dev/qa etc. But when i validate the above nginx configuration file with nginx -t, i get "proxy_set_header" directive is not allowed here. Hope you can help me to identify the problem with this code.
location ~^/reporting-(?<myvar>[a-zA-Z]+) {
if ($myvar = "ops") {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_pass https://xx.xx.xx.xx:8080/reporting;
}
if ($myvar = "dev") {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_pass https://xx.xx.xx.xx:8083/reporting;
}
}
Hi Thank You Timo. i am sure that this solution is fundamentally correct. But i'm still struggling with the url rewriting. in order to test this, i applied below code.
location /reporting-ops {
proxy_set_header Host $host;
rewrite ^/reporting-ops/(.*) /reporting/$1 break;
proxy_pass http://192.168.1.25:8931/reporting/$1; #option 1
# proxy_pass http://192.168.1.25:8931/$1; # option 2
}
But when i do this my browser url changes to /reporting like below. i think browser-url shouldn't change & the rewriting should happen when the request reach nginx.
Upvotes: 2
Views: 6634
Reputation: 3071
You should really try to avoid if in this use case. https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/
Furthermore the proxy_set_header
directive is NOT allowed in the context of if
. https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_set_header
I would use a map
to to this
map $uri $upstream {
~^/reporting-dev/ 1.2.3.4:8080;
~^/reporting-qa/ 1.2.3.4:8081;
default 1.2.3.4:8082;
}
server {
location ~^/reporting-([a-zA-Z]+)/ {
proxy_set_header Host $host;
proxy_redirect off;
proxy_pass http://$upstream/reporting;
}
}
If you need to rewrite the $uri
to pass anything "behind" reporting-aq|dev to the upstream do this.
map $ruri $upstream {
~^/reporting-dev/ 127.0.0.1:8080;
~^/reporting-qa/ 127.0.0.1:8081;
}
server {
#Keep the requested URI before! we rewrite it for the upstream
set $ruri $uri;
location / {
return 200 "No match\n";
}
location ~ ^/reporting-([a-zA-Z]+)/ {
proxy_set_header Host $host;
#rewrite the URI to get anything but reporting-qa|dev
rewrite /reporting-([a-z]+)/(.*) /reporting/$2 break;
proxy_pass http://$upstream;
}
}
server {listen 8080; return 200 "OK DEV = $host$request_uri\n";}
server {listen 8081; return 200 "OK QA = $host$request_uri\n";}
Upvotes: 1