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 responded with the 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 that 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 responded with "HTTP 307 Temporary Redirect"
        # then this section will be used
        # 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, I'm a passionate Tech Lead DevOps Engineer. 👋

With 16+ years of open-source contributions, 12+ years of professional hands-on experience in DevOps, and an M.Sc. in Data Engineering from Edinburgh Napier University (UK), I enjoy facilitating the growth of both businesses and individuals.

I specialize in Cloud-Native and Kubernetes. I'm also a Free/Open source geek and book author. My favorite topics are DevOps transformation, automation, data, and metrics.

Contact Me

Name

Email *

Message *

Start Your DevOps Engineer Journey!

Start Your DevOps Engineer Journey!
Start your DevOps career for free the Agile way in 2024 with the Dynamic DevOps Roadmap ⭐

Latest Post

2023 Highlights

Image generated with Craiyon . Finally, 2023 is over! What a year! One more crazy year, but it was the culmination ...

Popular Posts

Blog Archive