03/10/2016

Resolve redirection internally from upstream - Nginx.

For a reason or another, you maybe have a situation where you need to resolve redirection internally from upstream in Nginx. i.e when you request a URL and an upstream responds with location of redirection (whatever the location of redirection is).

Maybe it's not best thing to do (performance wise), but sometimes it's handy enough for a certain use case e.g. when the redirection is done in upstream not Nginx itself or when you have "HTTP 307 Temporary Redirect" or whatever the case.

So all what you need is using "upstream_http_location" with redirection location as following:

upstream apps {
    server 10.0.0.1:8080;
    server 10.0.0.2:8080;
    server 10.0.0.3:8080;
}

server {
    listen 80;
    server_name example.com;

    # If the request went to one of upstreams and it has a "location" header.
    # this will follow the redirection.
    location @auto_redirect {
        set $redirection_url $upstream_http_location;
        proxy_pass $redirection_url;
    }

    location / {
        proxy_pass http://apps;
        recursive_error_pages on;

        # If upstream respond with "HTTP 307 Temporary Redirect" then
        # this will use this section which will redirect the request to another upstream.
        proxy_intercept_errors on;
        error_page 307 = @auto_redirect;
    
        # Rest of options.
    }
}

As it descried, If an upstream responded with "HTTP 307 Temporary Redirect" then this will use this section which will redirect the request to another upstream.

And of course you can use any of HTTP redirection codes (e.g. 301, 302, etc) based on your need.

Powered by Blogger.

Hello, my name is Ahmed AbouZaid and this is my "lite" technical blog!

I'm a passionate DevOps, Linux system administrator, RedHat Certified Engineer (RHCE), AWS SysOps/Solutions Architect, Free/Open source geek, author, interested in environment, calligraphy, and I believe that “Details Matter”!

Automation, data, and metrics are my preferred areas. I have a built-in monitoring chip, and too lazy to do anything manually :D

Popular Posts