Htaccess security rules

Security is one of the primary factor for a well made website. Without security, you may expose confidential information to users or allow hackers to destroy your website.

Using htaccess, you can add various rules to harden security. Some of them are quite easy to implement just by adding a few lines in .htaccess file on your webserver.

Disable the server signature:

Server Signature display version number of Apache Server, Operating System, and modules installed. If your server display this kind of information publicly, Hackers can use it in order to exploit vulnerabilities (specially for older versions).

It is recommended to hide all sensitive information inside Server Signature Information. This can be done by following simple code in htaccess.

ServerSignature Off

Disable directory listing:

This .htaccess code will remove directory indexing with 403 forbidden message. This helps tighten security by hiding code and files which can be misused by hackers.

Options All -Indexes

Password Protect a File:

If you have confidential files that you want to protect from public, you can use .htaccess and .htpasswd file.


#Protect Directory
AuthName "Dialog prompt"
AuthType Basic
AuthUserFile /home/mywebsite/public_html/private/.htpasswd
require valid-user

Generate password using various tools online such as hostingcanada or web2generators and put in .htpasswod file.



Prevent Image Hot Linking:

Hotlink with when some website links your images or other files which can greatly your impact your hosting bandwidth. You can prevent image hotlinking using htaccess code.

Code to block image & css files:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)? [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ [NC,R,L]

Here, images and CSS files will be blocked for all website except ours and it will show other/warning image. You can include other static files if needed. Read more about Htaccess Hotlink protection

Redirect Http to Https:

HTTPS allows secure communication between your browser and the server. If you have an SSL certificate, you can redirect all http (non-secure) URLs to secure https.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$$1 [R=301,L]

Read more about htaccess redirection here.

Deny Access to .htaccess Itself:

This code will deny access to .htaccess file itself.

# Deny access to .htaccess
<Files .htaccess>
Order allow,deny
Deny from all

Prevent access to certain files:

# Deny access to files with extensions .ini, .sh
<FilesMatch "\.(ini|sh)$">
Order allow,deny
Deny from all

# Deny access to filenames starting with dot(.)
<FilesMatch "^\.">
Order allow,deny
Deny from all

Learn more about Htaccess deny access

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.