Nginx disable .htaccess and hidden files but allow .well-known directory

I have a Nginx server, and disabled hidden files in the nginx_vhost.conf

## Disable .htaccess and other hidden files
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }

But LetsEncrypt needs access to the .well-known directory.

How do I allow the .well-known directory and deny the other hidden files?


Solution 1:

The other solutions did not helped me.

My solution is to include a negative regex for .well-known. Your code block should look like this then:

## Disable .htaccess and other hidden files
location ~ /\.(?!well-known).* {
    deny all;
    access_log off;
    log_not_found off;
}

It will block every dot file except the ones starting with .well-known

P.S.: I would also add return 404; to the block.

Solution 2:

Nginx applies locations with regular expressions in the order of their appearance in the configuration file.

Therefore, adding an entry like this just before your current location it will help you.

location ~ /\.well-known { 
    allow all;
}

Solution 3:

I've provided a full step by step tutorial on how to use Let's Encrypt with NGINX on my website.

The key parts are:

  • The official client is only ok, and is really poor on Amazon Linux. I recommend a different client, ACME.
  • Use this location for the webroot method, with my recommend client. Note that the requests are served over http, not https.

You don't need listeners in your https block at all, it's all done on https. This is only to prove you control the domain, it's not serving anything private or secret.

# Answer let's encrypt requests, but forward everything else to https
server {
  listen       80;
  server_name  example.com www.example.com
  access_log  /var/log/nginx/access.log main;

  # Let's Encrypt certificates with Acmetool
  location /.well-known/acme-challenge/ {
    alias /var/www/.well-known/acme-challenge/;
  }

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

Full step by step guide linked above.