When it comes to security, one should put lot of care to implement it correctly at every layer. In a Apache based server, you can configure your web server for security via .htaccess file.

Here are some common security configurations that can be implemented in the .htaccess file to enhance the security of your web application:

Prevent directory listing: To prevent directory listing and to deny access to all files and folders within a directory, add the following line to your .htaccess file:

Options -Indexes
  1. Restrict access by IP address: To restrict access to your website or specific directories by IP address, you can use the following code:
order deny,allow
deny from all
allow from 192.168.1.1

Replace 192.168.1.1 with the IP address you want to allow. You can also specify multiple IP addresses or IP ranges.

  1. Block access to specific file types: You can block access to specific file types (e.g., PHP files) by adding the following lines to your .htaccess file:
Order Deny,Allow Deny from all

This code will deny access to all PHP, HTML, and HTM files.

Prevent hotlinking: To prevent hotlinking (i.e., when other websites link to your images or files), add the following code to your .htaccess file:

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www.)?yourwebsite.com [NC]
RewriteRule .(jpg|jpeg|png|gif)$ - [NC,F,L]

This code will prevent any website from linking directly to your images or files.

Change default document: To change the default document (e.g., index.html or index.php) for your website, add the following line to your .htaccess file:

DirectoryIndex your_new_document.html

Enable HTTPS: To force HTTPS (i.e., to encrypt all communication between your website and users), add the following lines to your .htaccess file:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

These are just a few examples of the security configurations that can be implemented in the .htaccess file. Remember to always backup your .htaccess file before making any changes and test your website thoroughly after implementing any security

By Abhishek K.

Author is a Architect by profession. This blog is to share his experience and give back to the community what he learned throughout his career.