Block access to hidden files and directories (those starting with a dot, like .env, .git, or .htaccess) using .htaccess, you need to use mod_rewrite. This is because standard <FilesMatch> directives cannot block access to entire hidden directories in .htaccess context.
Rule
Add the following lines to the .htaccess file in your website is root directory (usually public_html):
RewriteEngine On
RewriteRule (^|/).(?!well-known/) - [F]
How it works?
- (^|/).: Matches a dot at the beginning of the path (^.) or right after a slash (/.), effectively targeting any file or folder whose name starts with a dot.
- (?!well-known/): This is a negative lookahead. It excludes the .well-known directory, which is essential for SSL certificate validation (Let is Encrypt) and other standard protocols. Without this exclusion, you might break HTTPS on your site .
- - [F]: The - means "do nothing to the URL," and [F](Forbidden) instructs Apache to return a 403 Forbidden error, blocking access .
Alternative: Blocking Specific Hidden Files Only
If you only want to protect specific files (like .htaccess or .env) but don not need to block entire hidden directories, you can use a <FilesMatch> block. This is simpler but less comprehensive than the rewrite rule above .
<FilesMatch "^.">
Order Allow,Deny
Deny from all
</FilesMatch>