How to deny access to a file in .htaccess

Timothée HENRY picture Timothée HENRY · Jul 30, 2012 · Viewed 208.3k times · Source

I have the following .htaccess file:

RewriteEngine On
RewriteBase /

# Protect the htaccess file
<Files .htaccess>
Order Allow,Deny
Deny from all
</Files>

# Protect log.txt
<Files ./inscription/log.txt>
Order Allow,Deny
Deny from all
</Files>

# Disable directory browsing
Options All -Indexes

I am trying to forbid visitors to access the following file:

domain.com/inscription/log.txt

but what I have above does not work: I can still access the file from the browser remotely.

Answer

Jon Lin picture Jon Lin · Jul 30, 2012

Within an htaccess file, the scope of the <Files> directive only applies to that directory (I guess to avoid confusion when rules/directives in the htaccess of subdirectories get applied superceding ones from the parent).

So you can have:

<Files "log.txt">  
  Order Allow,Deny
  Deny from all
</Files>

For Apache 2.4+, you'd use:

<Files "log.txt">  
  Require all denied
</Files>

In an htaccess file in your inscription directory. Or you can use mod_rewrite to sort of handle both cases deny access to htaccess file as well as log.txt:

RewriteRule /?\.htaccess$ - [F,L]

RewriteRule ^/?inscription/log\.txt$ - [F,L]