HTTP to HTTPS redirects in nginx done right

Wrong

Rewriting the traffic from HTTP->HTTPS is a standard procedure these days. Mostly because of convenience, the HTTP port is still open.

As you can se below, there is a common pattern using the rewrite directive in nginx:

server {
    listen *:80;
    server_name my-site.example.com;
    rewrite ^(.*) https://$host$1 permanent;
}

server {
    listen *:443;
    server_name my-site.example.com;
    # The actual server configuration now
    root /var/www/my-site.example.com;
    [...]
}

This results in a HTTP Response with status code 301, pointing to the given URL in the second argument.

$host might not evaluate to a your desired host

$host is a valid

The regex must be processed

Regex parsing is quite expensive on the computing side. All this regex does is capturing the full Request URI. Why do you need to capture this, when you’ve got already the $request_uri variable pre-filled?

Consider

Use return

ACME (Letsencrypt) does not work