How to redirect all http traffic to https using nginx

2024-02-26

A few gotchas:

  1. Comment out everything in the default nginx config, for the default block to work here: /etc/nginx/sites-available/default Otherwise, you would likely get errors wrt multiple default_server's.
  2. Run sudo nginx -t to check if your config is valid
  3. Run sudo systemctl reload nginx to apply your checked config

Here is a nginx config that you might want to start with, this configuration snippet tells Nginx to listen for all HTTP traffic (both IPv4 and IPv6) on port 80, regardless of the domain name requested, and to redirect all of those requests to the HTTPS equivalent URL, using a 301 Moved Permanently response. This is a common setup for enforcing HTTPS across a website, ensuring that all traffic is encrypted:

server {
	listen 80 default_server;
	listen [::]:80 default_server;
	server_name _;
	return 301 https://$host$request_uri;
}

server {

This line begins the definition of a server block. Everything between the curly braces {} is part of the server block configuration. It tells Nginx that we're starting to define a new set of directives (rules) for how a particular site or service should be handled.

listen 80 default_server;

listen [::]:80 default_server;

This line is very similar to the previous one, but it's for IPv6 addresses.

server_name _;

return 301 https://$host$request_uri;

Sources: