nginx conditional proxy pass

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.


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;
    }

}

Tags:

Nginx

Proxy