Advanced .htaccess security and block access using .htaccess file

Block access to files using htaccess

1. Block access to .htaccess file
Add the following code block to your htaccess file to add an extra layer of security.Any attempts to access the htaccess file will result in a 403 error message.Your first layer of security to protect htaccess files involves permissions via CHMOD to 644.

# secure your htaccess file
<Files .htaccess>
order allow,deny
deny from all
</Files>

2. Block access to a Specific File
To restrict access to a specific file, add the following code block and edit the file name, “secure_file.jpg”, with the name of the file that you wish to protect.

# prevent viewing of a specific file
<files secure_file.jpg>
order allow,deny
deny from all
</files>

3. Block access to multiple file types
To restrict access to a variety of file types, add the following code block and update the file types within parentheses to match the extensions of any files that you wish to protect.

<FilesMatch “\.(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$”>
Order Allow,Deny
Deny from all
</FilesMatch>

4. Block unauthorized Directory Browsing
Prevent unauthorized directory browsing by instructing the server to serve a “xxx Forbidden – Authorization Required” message for any request to view a directory. For example, if your site is missing it’s default index page, everything within the root of your site will be accessible to all visitors. To prevent this, include the following htaccess rule.

# disables directory browsing
Options All -Indexes

To enable directory browsing, use the following directive.

# enables directory browsing
Options All +Indexes

Likewise, this rule will prevent the server from listing directory contents.

# prevent folder listing
IndexIgnore *

And, finally, the IndexIgnore directive may be used to prevent the display of select file types.

# prevent display of select file types
IndexIgnore *.wmv *.avi *.mp4 *.etc