Search code examples
.htaccess

How to deny access to a file in .htaccess


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.example/inscription/log.txt

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


Solution

  • 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]