Home > Software engineering >  .htaccess deny dot-files but allow letsencrypt
.htaccess deny dot-files but allow letsencrypt

Time:10-20

My goal is to deny access to all dot-files e.g .htaccess, .env and send back a 404, but allow the letsencrypt-folder .well-known to be accessed

RewriteEngine On
RewriteRule "(^|/)\.(?!well-known)" - [F]
RedirectMatch 404 /\..*$

Any hint on how to achieve this is highly appreciated Best endo

CodePudding user response:

Try the following instead:

RewriteEngine On

RewriteRule (?:^|/)\.[^/] $ - [R=404]

This will serve a 404 for any file (or rather, last URL-path segment) that starts with a dot. But it will permit .well-known/ - since this is a directory and so is also suffixed by at least a slash filename.

UPDATE: Modified regex so that it matches the dot at the start of the last path-segment, rather than anywhere in the last path-segment!

Note that the F flag responds with a 403 Forbidden, not a 404 as requested.


Alternatively, you can use a <Files> (or <FilesMatch>) container, which only matches "files". For example:

<Files ".*">
    # 404 Not Found
    Redirect 404 /

    # OR... 403 Forbidden
    #Require all denied
</Files>

Although this does also block a request for /.well-known (no trailing slash) - although that's not strictly a valid request anyway.

  • Related