20 Useful Apache '.htaccess' Tricks to Secure and Customize Websites

Apache is one of the most popular web servers in the world, used by millions of websites to serve content to users. One of its most powerful features is the 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 the server's behavior.

Password Protect a Directory

To protect a directory on your website with a password, use the following .htaccess code:

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

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

Block Visitors by IP Address

To block visitors from certain IP addresses or ranges, use the following .htaccess code:

Order Allow,Deny
Deny from 123.45.67.89

Replace 123.45.67.89 with the 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.

This will block all IP addresses that start with 123.45.67.

Redirect Visitors to a New URL

To redirect visitors from one URL to another, use the following .htaccess code:

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

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

Force HTTPS

To force visitors to use HTTPS instead of HTTP, use the 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

To prevent Apache from listing the contents of a directory when no index file is present, use the following .htaccess code:

Options -Indexes

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

Set Custom Error Pages

To provide custom error pages for various HTTP errors, use the following .htaccess code:

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

Replace /404.html and /500.html with the 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

To compress your website's files with Gzip to reduce their size and speed up page load times, use the 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

To prevent visitors from accessing certain file types on your website (such as .sql or .conf files), use the 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

To limit the maximum file size that visitors can upload to your website, use the following .htaccess code:

php_value upload_max_filesize 10M
php_value post_max_size 10M

Replace 10M with the 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

To block access to your website from certain user agents (such as web crawlers or malicious bots), use the following .htaccess code:

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

Replace bad-bot with the 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

To redirect visitors who access your website without the "www" prefix to the version with it, use the 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 the visitor's browser.

Disable Server Signature

To hide the version number and other information about your server in HTTP headers, use the following .htaccess code:

ServerSignature Off

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

Limit Access to Specific HTTP Methods

To restrict access to your website to only certain HTTP methods (such as GET and POST), use the 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

To block access to your website from certain referrers (such as spammy websites or malicious domains), use the following .htaccess code:

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

Replace spammydomain.com with the 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 Extensions

To set specific MIME types for certain file extensions on your website, use the following .htaccess code:

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

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

Disable Hotlinking

To prevent other websites from linking directly to images or other media on your website (also known as hotlinking), use the 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.

Add Security Headers

To add security-related HTTP headers to all requests on your website, use the following .htaccess code:

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

These headers help protect against clickjacking, cross-site scripting (XSS), and MIME type sniffing attacks. The X-Frame-Options header prevents your site from being embedded in frames, X-XSS-Protection enables browser XSS filtering, and X-Content-Type-Options prevents MIME type confusion attacks.

Best Practices

Practice Description
Backup First Always backup your .htaccess file before making changes
Test Thoroughly Test your website after implementing new .htaccess rules
Use Comments Add comments to document what each rule does
Start Simple Begin with basic rules and gradually add complexity

Conclusion

The .htaccess file is a powerful tool for securing and customizing Apache websites. These 20 tricks can help you block malicious traffic, optimize performance, and enhance security. However, always backup your .htaccess file before making changes and test thoroughly, as a single mistake can cause errors or take down your website.

Updated on: 2026-03-16T23:25:01+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements