Protect .htaccess files

Category: Blog • Posted by Jeff Starr • Post Date:

By default on properly configured servers, the .htaccess and .htpasswd files are protected from all external access. This is super important because you do not want anyone or anything to access these sensitive and powerful files. If you are unsure, or just want to be extra secure, continue reading to learn how to protect all of your .htaccess and .htpasswd files.

Test first

First, take a moment to request one of your .htaccess files in a browser. This will let you know if the files are accessible on the Web. You may also want to try requesting the file using other, non-browser techniques such as Telnet, SSH, et al. All should be locked down by default; if not, ask your host why .htaccess files are accessible to the public. In either case, if you want to lock things down or add an extra layer of security just to be safe, continue reading for various techniques.

Protect with Apache Core

The following techniques can be used to secure the .htaccess and .htpasswd files on any Apache server.

Protect .htaccess

# protect .htaccess
<Files ~ "^.*\.([Hh][Tt][Aa])">
	Order allow,deny
	Deny from all
	Satisfy all
</Files>

Protect .htpasswd

# protect .htpasswd
<Files ~ "^.*\.([Hh][Tt][Pp])">
	Order allow,deny
	Deny from all
	Satisfy all
</Files>

Protect both files

# protect .htaccess and .htpasswd
<Files ~ "^.*\.([Hh][Tt])">
	Order allow,deny
	Deny from all
	Satisfy all
</Files>

Protect all files beginning with a dot

# protect all dot files
<Files ~ "^.*\.">
	Order allow,deny
	Deny from all
	Satisfy all
</Files>

Protect with mod_alias

Here is a simple .htaccess snippet that will protect all files that begin with a dot:

# protect files beginning with .
RedirectMatch 403 /\.(.*)

This will protect all .htaccess files, .htpasswd files, and any other file that begins with a literal dot. You could refine the technique a bit by requiring that the dot be proceeded by the letters “ht”:

# protect files beginning with .ht
RedirectMatch 403 /\.ht(.*)

This is more specific, so better if you are concerned about false positives.

Protect with mod_rewrite

Here is the same basic technique as before, but using Apache's mod_rewrite and RewriteRule:

# protect files beginning with .
RewriteRule /\.(.*) - [NC,F]

As before, this could be tweaked to be more specific, requiring the letters “ht”.