How to redirect all http to https in NGINX

Find your NGINX configuration:


Add the following include inside the http block:

include /etc/nginx/snippets/redirect-to-https.conf;
Code language: PHP (php)

Create the snippet file we just included. It should have this content:

server { listen 80 default_server; server_name _; return 301 https://$host$request_uri; }
Code language: Bash (bash)

Remember to test your NGINX configuration before reloading:

nginx -t
systemctl reload nginx

What is happening here?

This server block will listen to the 80 port which is the HTTP port (the HTTPS port is 443).

We're indicating the server_name to simply be underscore, which means any server name.

Finally, if it has entered in this rule it means we're in HTTP (remember we're telling this block to listen to port 80), redirect to the HTTPS location.

About Ricard Torres

Senior Front-end Software Engineer at Netcentric, from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.

@ricard_dev @ricard_dev

📝 Blog 🎙 Podcast

Leave a Reply

Add <code> Some Code </code> if you need to.