Nginx http to https Redirect

A few days ago changed the site over to have https as an option; today I just changed nginx to respond to http with a 301 and redirect to the https version.

Not hard at all.


Important Note: I did take a backup of my server prior to starting these changes. I strongly recommend this.

I added something like the following to my applications server subsection.

server {
   listen 80;
   listen [::]:80;
   return 301 https://$server_name$request_uri;

server {
   # listen 80; #Redirect to https above. (This is commented out)
   # listen [::]:80;
   listen 443; 
   # ... the rest #

So were defining a server block to handle port 80; I've seen it done with a condition too and I like that this worked as it's more straightforward.

So if it comes in on this server block, it nginx returns a 301 and the appropriate version of the URL before it even gets to express/ghost.

I checked the syntax I typed (manually) via sudo nginx -t. It passed and so I restarted nginx with: sudo systemctl reload nginx.

Everything worked very well.

Frank Villasenor

Frank Villasenor

Owner and principal author of this site. Professional Engineering Lead, Software Engineer and Architect working from the Chicagoland area for healthcare SaaS company. Cert: AWS DevOps Professional
Chicago, IL