Because I always forget, if you're using certbot to create certs for your Nginx server, you'll need to it up so it works on HTTP as well as HTTPS. But once you're done, you're going to want all HTTP traffic to redirect to HTTPS. The correct syntax is:


server {
    server_name mydomain.example.com;
    include /etc/nginx/snippets/letsencrypt-acme-challenge.conf;
    location / {
      return 301 https://mydomain.example.com$request_uri;
    }
}

And that letsencrypt-acme-challenge.conf looks like this (code comments stripped):


location ^~ /.well-known/acme-challenge/ {
    default_type "text/plain";
    root         /var/www/html;
    break;
}
location = /.well-known/acme-challenge/ {
    return 404;
}

This way, a GET request for http://mydomain.example.com/.well-known/acme-challenge/test.html will be 200 OK if there's a file called /var/www/html/.well-known/acme-challenge/test.html. And http://mydomain.example.com/.well-known/acme-challenge/does-not-exist.html will 404 Not Found.

But all and any other GET request will redirect. E.g. http://mydomain.example.com/whatever -- 301 Moved Permanently --> https://mydomain.example.com/whatever.

Comments

John

Thank you, this was very helpful!

Your email will never ever be published.

Previous:
How I upload Firebase images optimized September 2, 2021 Web development, Firebase, JavaScript
Next:
TypeScript function keyword arguments like Python September 8, 2021 Python, JavaScript
Related by category:
brotli_static in Nginx November 8, 2024 Nginx
Be very careful with your add_header in Nginx! You might make your site insecure February 11, 2018 Nginx
Make your NextJS site 10-100x faster with Express caching February 18, 2022 Nginx
How I simulate a CDN with Nginx May 15, 2019 Nginx
Related by keyword:
redirect-chain - Getting a comfortable insight input URL redirects history February 14, 2020 Python
How I installed letsencrypt for Nginx January 26, 2016 Linux, Web development
www aliases set up November 1, 2005 This site