How to forward all http requests to https without breaking letsencrypt with nginx

Dean MacGregor asked:

I’m using Nginx to serve as a reverse proxy for Rstudio server and Shiny server for the purposes of securing the connection to these services. I’m using Letencrypt for free signed certs.

I have this entry for letsencrypt to verify I am who I say I am.

server { 
  listen 80 default_server;
  listen [::]:80 default_server ipv6only=on;

  root /usr/share/nginx/html;
  index index.html index.htm;

  # Make site accessible from http://localhost/
  server_name mydomain.com;

  location ~ /.well-known {

    allow all;
  }
}

I also have another server to listen on 443 and proxy_redirect to my servers. Everything there works fine. What I want to do is have something like

server {
listen 80;
return 301 https://$host$request_uri;
}

but I think this will break letsencrypt so how do I have the above without breaking letsencrypt verification?

My answer:


My working configuration for this is:

server {
         listen 80;
         listen [::]:80;
         server_name example.com www.example.com;

         root /srv/www/empty;

         include includes/letsencrypt;

         location / {
                 return 301 https://www.example.com$request_uri;
         }
}

where /etc/nginx/includes/letsencrypt is Ansible managed and contains:

location /.well-known/acme-challenge/ {
         try_files $uri =404;
}

and /srv/www/empty is an otherwise empty directory, which only contains files when Let’s Encrypt is being used to issue a challenge (with --webroot).

Let’s Encrypt is then run with:

letsencrypt certonly --webroot -w /srv/www/empty -d example.com -d www.example.com

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.