hazardous

thoughts, things, etc. from andrew snow

nginx odds and ends: redirects

nginx! a cruel mistress.

through the years i have deployed nginx as a wonderful solution for alot of projects. however, i never really perfected a good 'one size fits all' nginx config - no single set of files that would require only a small amount of tweaking to fit a wide variety of use cases. this will be my attempt to come to understand nginx, from the ground up.

redirects

serving one site is easy, serving two is trickier, but to add url redirects on top while keeping everything secured by TLS was a big more complex than i thought!

the challenge: making sure that visiting hazardous would always send the user to the proper URL: https://ha.zardo.us, regardless of the URL actually followed - all http:// sites would redirect to the secure https:// protocol, and visitors coming via zardo.us or www.zardo.us would redirect to ha.zardo.us.

the internet was filled with a variety of ways to do this, but none of them quite seemed to work for my own use case: some solutions were there for redirecting http to https, and other solutions were out there to redirect a top-level domain to a subdomain. i'm proud to say that my solution came from endlessly experimenting with the various suggested methods to create my own solution, here:

zardo.us.conf

server {
        listen 80;
        listen [::]:80;
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
        server_name www.zardo.us zardo.us;
            return 301 https://ha.zardo.us$request_uri;
}

server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;

       server_name ha.zardo.us;
   [...]
}

it avoids relying on if then conditions and allows nginx itself to do most of the "heavy lifting", by creating a server block to catch all 'bad' traffic going to www.zardo.us and zardo.us, over port 80 (http) and port 443 (https). it issues a single 301 redirect towards the 'good' url: ha.zardo.us served only over https via port 443.