Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx conditional proxy pass

Tags:

nginx

proxy

i am trying to configure nginx to proxy pass the request to another server, only if the $request_body variable matches on a specific regular expression.

My problem now is, that I don't how to configure this behaviour exactly.

I am currently down to this one:

server {     listen 80 default;     server_name test.local;      location / {             proxy_set_header X-Real-IP $remote_addr;             proxy_set_header X-Forwarded-For $remote_addr;             proxy_set_header Host $http_host;              if ($request_body ~* ^(.*)\.test) {                     proxy_pass http://www.google.de;             }              root /srv/http;     }  } 

but the problem here is, that root has always the upperhand. the proxy won't be passed either way.

any idea on how I could accomplish this?

thanks in advance

like image 983
sharpner Avatar asked Oct 24 '11 15:10

sharpner


2 Answers

try this:

server {     listen 80 default;     server_name test.local;      location / {         proxy_set_header X-Real-IP $remote_addr;         proxy_set_header X-Forwarded-For $remote_addr;         proxy_set_header Host $http_host;          if ($request_body ~* ^(.*)\.test) {             proxy_pass http://www.google.de;             break;         }          root /srv/http;     }  } 
like image 111
user973254 Avatar answered Sep 22 '22 12:09

user973254


Nginx routing is based on the location directive which matches on the Request URI. The solution is to temporarily modify this in order to forward the request to different endpoints.

server {     listen 80 default;     server_name test.local;       if ($request_body ~* ^(.*)\.test) {          rewrite ^(.*)$ /istest/$1;      }       location / {          root /srv/http;      }       location /istest/ {         rewrite ^/istest/(.*)$  $1 break;          proxy_set_header X-Real-IP $remote_addr;         proxy_set_header X-Forwarded-For $remote_addr;         proxy_set_header Host $http_host;         proxy_pass http://www.google.de;      } } 

The if condition can only safely be used in Nginx with the rewrite module which it is part of. In this example. The rewrite prefixes the Request URI with istest.

The location blocks give precedence to the closest match. Anything matching /istest/ will go to the second block which uses another rewrite to remove /istest/ from the Request URI before forwarding to the upstream proxy.

like image 41
Steve E. Avatar answered Sep 23 '22 12:09

Steve E.