Redirect with nginx before hitting a load balancer

At work I often am presented tasks with no obvious solution.

Today’s problem was

We want to redirect x.rderewianko.com/some/url/here to y.rderewianko.com/some/url/here.

Simple right?

Wrong! x.company.com points to a Elastic Load Balancer that we don’t manage and is managed by a 3rd party that we pay to manage.

 

So the question became, can we put something in front of that, have it redirect to y.rderewianko.com/some/url/here? while maintaining x.company.com to provide urls as the fall back?

This problem in its own sounded simple, and to me I didn’t expect my solution to work.

The questions I had left to answer:

Will NGINX accept a url like x.rderewianko.com/some/url/here#gettingstarted

Will the Load balancer accept the reverse proxy traffic?

Will redirects work to redirect that traffic and fail to the load balancer?

Will the reverse proxy maintain the proper domain name with the load balancer?

Will this all work with SSL?

 

To answer these questions, I spun up a basic ami and installed nginx

I then searched and cobbled together a config file that I thought would work.

I found this gist that was a starting point.

I verified this worked to redirect all traffic, from https://x.rderewianko.com -> 3rd party AWS ELB

Then, I added a redirect unsecure traffic to secure traffic, with the server block and added a secondary file in my nginx config to deal with redirects. My reasoning for this was if someone else was to add redirects, its easier to have them add to a separate config file than the master. This can be seen in line 39.

 

My Redirect file looked like this:

 

It’s important to note, we are not telling the browser if this is a 301 or 302 redirect. We are however telling nginx, upon match to stop processing and redirect us. This can be done by putting a break instead of permanent at the end of the string.

If you’ve got a bunch of urls you need to redirect, there’s a few tools that make this easier.

I started with: https://github.com/jptannus/nginx-redirect-generator this got me half way there, but it was using permanent instead of break.

With a few simple edits, https://github.com/rderewianko/nginx-redirect-generator  will output a starting config with break instead.

 

To my surprise putting this together worked.

The questions above were all answered, and my POC was finished.

 

No Comments

Leave a Comment