20 Useful Apache ‘.htaccess’ Tricks to Secure and Customize Websites


Apache is one of most popular web servers in world, and it's used by millions of websites to serve content to users. One of most powerful features of Apache is its ability to use .htaccess files to customize and secure websites. An .htaccess file is a simple text file that can be placed in a website's root directory to control various aspects of server's behavior. In this article, we'll cover 20 useful Apache .htaccess tricks that can help you secure and customize your website.

Password Protect a Directory

If you want to protect a directory on your website with a password, you can use following .htaccess code −

AuthType Basic
AuthName "Restricted Area"
AuthUserFile /path/to/passwords/file
Require valid-user

Replace /path/to/passwords/file with path to a file containing your encrypted passwords. You can generate this file using a tool like htpasswd. When a user tries to access protected directory, they will be prompted to enter a username and password.

Block Visitors by IP Address

If you want to block visitors from certain IP addresses or ranges, you can use following .htaccess code −

Order Allow,Deny
Deny from 123.45.67.89

Replace 123.45.67.89 with IP address you want to block. You can also use wildcards to block a range of IP addresses −

Order Allow,Deny
Deny from 123.45.67.89

This will block all IP addresses that start with 123.45.67.89.

Redirect Visitors to a New URL

If you want to redirect visitors from one URL to another, you can use following .htaccess code −

Redirect 301 /old-url.html http://www.example.com/new-url.html

Replace /old-url.html with URL you want to redirect from, and http://www.example.com/new-url.html with URL you want to redirect to. This will send a permanent redirect (HTTP 301) to visitor's browser.

Force HTTPS

If you want to force visitors to use HTTPS instead of HTTP, you can use following .htaccess code −

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

This will redirect all HTTP requests to HTTPS. Make sure you have an SSL certificate installed on your server before enabling this.

Block Directory Listings

If you want to prevent Apache from listing contents of a directory when no index file is present, you can use following .htaccess code −

Options -Indexes

This will return a 403 Forbidden error to any visitor who tries to access directory.

Set Custom Error Pages

If you want to provide custom error pages for various HTTP errors, you can use following .htaccess code −

ErrorDocument 404 /404.html
ErrorDocument 500 /500.html

Replace /404.html and /500.html with URLs of your custom error pages. You can also use this to redirect visitors to a custom error page for any HTTP error code.

Compress Files with Gzip

If you want to compress your website's files with Gzip to reduce their size and speed up page load times, you can use following .htaccess code −

<IfModule mod_deflate.c>
   AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript
</IfModule>

This will compress all text-based files on your website (HTML, CSS, JavaScript, etc.) with Gzip.

Block Access to Specific File Types

If you want to prevent visitors from accessing certain file types on your website (such as .sql or .conf files), you can use following .htaccess code −

<FilesMatch "\.(sql|conf)$">
   Order allow,deny
   Deny from all
</FilesMatch>

Replace (sql|conf) with a pipe-separated list of file extensions you want to block. This will return a 403 Forbidden error to any visitor who tries to access files with those extensions.

Limit File Upload Size

If you want to limit maximum file size that visitors can upload to your website, you can use following .htaccess code −

php_value upload_max_filesize 10M
php_value post_max_size 10M

Replace 10M with maximum file size you want to allow. This will limit both file uploads and POST requests to that size.

Block Access to Specific User Agents

If you want to block access to your website from certain user agents (such as web crawlers or malicious bots), you can use following .htaccess code −

RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} bad-bot [NC]
RewriteRule .* - [F]

Replace bad-bot with user agent you want to block. This will return a 403 Forbidden error to any visitor who uses that user agent.

Redirect non-www to www

If you want to redirect visitors who access your website without "www" prefix to version with it, you can use following .htaccess code −

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

Replace example.com with your own domain name. This will send a permanent redirect to visitor's browser.

Disable Server Signature

If you want to hide version number and other information about your server in HTTP headers, you can use following .htaccess code −

ServerSignature Off

This will prevent Apache from displaying server signature information in HTTP headers.

Limit Access to Specific HTTP Methods

If you want to restrict access to your website to only certain HTTP methods (such as GET and POST), you can use following .htaccess code −

<LimitExcept GET POST>
   Order Deny,Allow
   Deny from all
</LimitExcept>

This will block access to all HTTP methods except GET and POST.

Block Access to Specific Referrers

If you want to block access to your website from certain referrers (such as spammy websites or malicious domains), you can use following .htaccess code −

RewriteEngine on
RewriteCond %{HTTP_REFERER} spammydomain\.com [NC]
RewriteRule .* - [F]

Replace spammydomain.com with domain name you want to block. This will return a 403 Forbidden error to any visitor who comes from that domain.

Set MIME Types for Specific File Eextensions

If you want to set specific MIME types for certain file extensions on your website, you can use following .htaccess code −

AddType text/html .html
AddType application/json .json

Replace .html and .json with file extensions you want to set MIME types for. This will ensure that correct MIME type is sent in HTTP headers for those file types.

Disable Hotlinking

If you want to prevent other websites from linking directly to images or other media on your website (also known as "hotlinking"), you can use following .htaccess code −

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?example.com/.*$ [NC]
RewriteRule \.(gif|jpg|jpeg|bmp|png)$ - [F]

Replace example.com with your own domain name and (gif|jpg|jpeg|bmp|png) with a pipe-separated list of file extensions you want to protect. This will return a 403 Forbidden error to any visitor who tries to hotlink images or other media on your website.

Customize Error Pages

If you want to customize default error pages that Apache displays (such as 404 Not Found or 500 Internal Server Error), you can use following .htaccess code −

ErrorDocument 404 /404.html
ErrorDocument 500 /500.html

Replace 404.html and 500.html with names of your own error pages. This will display your custom error pages instead of default Apache ones.

Redirect to HTTPS

If you want to redirect visitors to secure HTTPS version of your website, you can use following .htaccess code −

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

This will redirect all HTTP requests to HTTPS.

Prevent Directory Listing

If you want to prevent visitors from viewing a list of files in a directory on your website, you can use following .htaccess code −

Options -Indexes

This will return a 403 Forbidden error to any visitor who tries to view a directory listing.

Add Custom Headers

If you want to add custom HTTP headers to all requests on your website, you can use following .htaccess code −

Header set X-Frame-Options "SAMEORIGIN"
Header set X-XSS-Protection "1; mode=block"
Header set X-Content-Type-Options "nosniff"

Replace X-Frame-Options, X-XSS-Protection, and X-Content-Type-Options with names of headers you want to set, and their respective values. This will add those headers to all HTTP responses on your website.

Conclusion

In conclusion, .htaccess file is a powerful tool that can be used to secure and customize your website in many ways. With 20 tricks discussed in this article, you can block malicious traffic, optimize your website for search engines, and enhance user experience. However, it is important to use caution when making changes to .htaccess file, as a single mistake can cause errors or even take down your website. Always make a backup of your .htaccess file before making any changes, and test your website thoroughly after implementing any new code.

Updated on: 28-Mar-2023

837 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements