The .htaccess
file is a powerful configuration file used on Apache-based web servers to manage and modify settings at the directory level. By modifying .htaccess
file, you can control many aspects of your website’s behavior without needing to alter server-wide settings.
Below are 25 essential .htaccess
tricks and tips that can help improve your site’s security, performance, and SEO.
1. Redirect HTTP to HTTPS
If your site supports HTTPS, it’s important to redirect all traffic from HTTP to HTTPS to improve security and boost search engine rankings.
RewriteEngine On RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
2. Set a Custom 404 Error Page
First, you need to create the HTML file that will serve as your custom 404 error page under your website’s document root directory, then add this line to specify your custom 404 page. This page helps retain users who land on non-existent pages.
ErrorDocument 404 /404.html
3. Force File Downloads
To force a file to download instead of displaying it in the browser, use this directive:
<FilesMatch "\.(pdf|zip|doc)$"> ForceType application/octet-stream Header set Content-Disposition attachment </FilesMatch>
This will make files like PDFs or ZIPs download automatically when accessed.
4. Block Specific IP Addresses
To block users from certain IP addresses, add the following lines:
<Limit GET POST> order allow,deny deny from 123.456.789.000 allow from all </Limit>
5. Redirect Old URLs to New Ones
If you have changed the structure of your site, redirecting old URLs to new ones is critical for maintaining SEO.
Redirect 301 /old-url.html https://yourdomain.com/new-url.html
This sends a permanent redirect (301) from the old URL to the new one.
6. Password Protect a Directory
You can protect directories with a password by adding this to your .htaccess
file:
AuthType Basic AuthName "Restricted Area" AuthUserFile /path/to/.htpasswd Require valid-user
Create a .htpasswd
file for storing usernames and passwords.
htpasswd -c .htpasswd username
7. Disable Directory Browsing
By default, users may be able to see a list of files in a directory without an index page, but you can prevent this by disabling directory browsing.
Options -Indexes
This will show a 403 Forbidden error instead of the file list.
8. Restrict Access to .htaccess File
To protect your .htaccess
file from unauthorized access, add this rule:
<Files .htaccess> order allow,deny deny from all </Files>
This ensures that no one can view the contents of your .htaccess
file.
9. Block Hotlinking
Hotlinking occurs when another site directly links to your images, consuming your bandwidth. To prevent this, use:
RewriteEngine On RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{HTTP_REFERER} !^https://(www\.)?yourdomain.com [NC] RewriteRule \.(jpg|jpeg|png|gif)$ - [F]
Replace yourdomain.com
with your domain name.
10. Custom 403 Forbidden Page
Like custom 404 pages, you can create a custom 403 Forbidden page.
ErrorDocument 403 /403.html
This page appears when users try to access restricted content.
11. Prevent Image Hotlinking With a Warning Image
You can replace hotlinked images with a custom warning image:
RewriteEngine On RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{HTTP_REFERER} !^https://(www\.)?yourdomain.com [NC] RewriteRule \.(jpg|jpeg|png|gif)$ https://yourdomain.com/warning.jpg [R,L]
Replace warning.jpg
with your custom warning image.
12. Set Cache-Control Headers
To improve site performance, use .htaccess
to set cache control for static resources like images and scripts:
<FilesMatch "\.(jpg|jpeg|png|gif|js|css)$"> Header set Cache-Control "max-age=2592000, public" </FilesMatch>
This tells browsers to cache these files for 30 days (2592000 seconds).
13. Deny Access to Certain File Types
You may want to block access to certain file types, such as configuration files:
<FilesMatch "\.(ini|log|conf)$"> Order allow,deny Deny from all </FilesMatch>
14. Enable Gzip Compression
Gzip compression reduces the size of files sent to the browser, improving load times:
<IfModule mod_deflate.c> AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css AddOutputFilterByType DEFLATE application/javascript </IfModule>
15. Redirect to a Maintenance Page
If your site is undergoing maintenance, you can redirect all visitors to a specific maintenance page:
RewriteEngine On RewriteCond %{REQUEST_URI} !/maintenance.html$ RewriteRule ^(.*)$ /maintenance.html [R=307,L]
Replace maintenance.html
with your maintenance page URL.
16. Limit File Upload Size
To limit the file upload size on your site, use this rule:
php_value upload_max_filesize 10M php_value post_max_size 10M
17. Redirect Non-WWW to WWW
To ensure all traffic is directed to the www version of your domain:
RewriteEngine On RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
This will redirect visitors from yourdomain.com
to www.yourdomain.com
.
18. Redirect WWW to Non-WWW
If you prefer the non-www version of your domain, use this code:
RewriteEngine On RewriteCond %{HTTP_HOST} ^www\. [NC] RewriteRule ^(.*)$ https://yourdomain.com/$1 [L,R=301]
This redirects www.yourdomain.com
to yourdomain.com
.
19. Prevent Access to PHP Files in Specific Folders
You can block access to PHP files in specific directories (like uploads) for security:
<Directory "/path/to/uploads"> <Files "*.php"> Order Deny,Allow Deny from all </Files> </Directory>
Replace /path/to/uploads
with the actual folder path.
20. Prevent Image Directory Access
To block access to your image folder while still allowing images to load on your site:
<Directory "/path/to/images"> Order Deny,Allow Deny from all </Directory>
21. Block Specific User Agents
If certain bots or scrapers are abusing your site, you can block them:
RewriteEngine On RewriteCond %{HTTP_USER_AGENT} badbot [NC] RewriteRule .* - [F,L]
Replace badbot
with the user agent you want to block.
22. Restrict Access by Country
To block visitors from specific countries, you need access to a list of IP ranges for those countries.
Here’s an example for blocking certain IP ranges:
<Limit GET POST> order allow,deny deny from 123.456.789. allow from all </Limit>
You’ll need to replace the IP ranges with those specific to the countries you want to block.
23. Enable Cross-Origin Resource Sharing (CORS)
To allow CORS for resources like fonts or images, use:
<IfModule mod_headers.c> Header set Access-Control-Allow-Origin "*" </IfModule>
24. Prevent SQL Injection
You can block common SQL injection attempts:
RewriteEngine On RewriteCond %{QUERY_STRING} (\<|%3C)(script|SELECT|INSERT|UPDATE|DELETE|DROP|UNION|;|\-\-) [NC] RewriteRule .* - [F]
25. Allow Only Certain File Types in Uploads
You can restrict which file types can be uploaded to your site.
<FilesMatch "\.(php|cgi|pl|py)$"> Order Deny,Allow Deny from all </FilesMatch>
26. Enable File Access Logs
If you want to track access to specific files for auditing or monitoring purposes, you can enable logging for certain file types:
SetEnvIf Request_URI "\.(pdf|doc|mp3)$" requested_file CustomLog /path/to/logfile.log combined env=requested_file
This will log access to .pdf
, .doc
, and .mp3
files in a separate log file.
27. Custom 500 Internal Server Error Page
If your server encounters an internal error, you can display a custom error page to provide a better user experience.
ErrorDocument 500 /500.html
This way, instead of showing the default server error message, users will see a more user-friendly message that you have customized.
28. Prevent Access to Backup and Source Files
Backup files (like .bak
, .old
) or source files (like .log
) are sometimes left on servers, exposing sensitive information.
To prevent access to these files, add this:
<FilesMatch "\.(bak|old|log|sql)$"> Order allow,deny Deny from all </FilesMatch>
29. Limit Access by Referrer
You can control which sites are allowed to refer traffic to your website. For example, to block access to your site when the referrer comes from a specific domain.
RewriteEngine On RewriteCond %{HTTP_REFERER} ^https://www\.baddomain\.com [NC] RewriteRule .* - [F]
Replace baddomain.com
with the site you want to block as a referrer.
30. Limit Access to Admin Area by IP Address
If your website has an admin panel (like /admin
or /wp-admin
), it’s wise to limit access to this section based on IP address for security reasons:
<Files "admin.php"> Order Deny,Allow Deny from all Allow from 123.456.789.000 </Files>
Replace 123.456.789.000
with your IP address. Only this IP will be allowed to access admin.php
.
31. Custom 401 Unauthorized Error Page
When users attempt to access a restricted page without proper authentication, you can present a custom 401 Unauthorized error page instead of the default server message:
ErrorDocument 401 /401.html
32. Redirect Based on Language Preference
If you have a multilingual website, you can redirect users to the appropriate language version of your site based on their browser’s language settings:
RewriteEngine On RewriteCond %{HTTP:Accept-Language} ^fr [NC] RewriteRule ^$ /fr/index.html [L,R=302]
This example redirects users to French (fr
) language preference to the French version of your site.
33. Set Default Charset
You can specify the default character encoding for your website to ensure consistent text rendering across different browsers:
AddDefaultCharset UTF-8
This is particularly useful for websites that handle multiple languages or special characters.
34. Limit Request Methods
You can restrict which HTTP request methods (e.g., GET
, POST
) are allowed on your website to enhance security.
For instance, you might want to block dangerous methods like TRACE
or TRACK
:
<LimitExcept GET POST> Order Deny,Allow Deny from all </LimitExcept>
35. Restrict Access During Site Maintenance
If you want to put your site into maintenance mode but allow certain IPs (like your own) to access the site, use this:
RewriteEngine On RewriteCond %{REMOTE_ADDR} !^123\.456\.789\.000$ RewriteCond %{REQUEST_URI} !/maintenance.html$ RewriteRule ^(.*)$ /maintenance.html [R=302,L]
Replace 123.456.789.000
with your IP address. Only visitors from that IP will be able to access the site while others will see a maintenance page.
36. Set Cache-Control Headers
Caching helps improve the performance of your site by storing copies of files in users’ browsers. You can set cache control headers to tell browsers how long to cache certain types of files:
<IfModule mod_expires.c> ExpiresActive On ExpiresDefault "access plus 1 month" ExpiresByType image/jpg "access plus 1 year" ExpiresByType image/png "access plus 1 year" ExpiresByType image/gif "access plus 1 year" ExpiresByType text/css "access plus 1 month" ExpiresByType application/javascript "access plus 1 month" </IfModule>
This example sets a longer cache time for images compared to CSS or JavaScript.
Conclusion
These .htaccess
tips and tricks can significantly enhance your website’s security, performance, and user experience. Always make a backup of your .htaccess
file before making changes and test the configuration to ensure your site behaves as expected.
Hi Sir,
Someone hacked our website and always take it index.php file instead of a different php file.
Also, the htaccess file gets created newly even we deleted it.
Great htaccess tips, Thanks for sharing this helpful article. can you please give some suggestions about .htaccess security?
@Sajjad,
Use the following directive to secure and restrict access to .htaccess file on the server.
Hey Tosin,
i don’t think about any ebook related htaccess because htaccess is part of logic which is every one can modified using his ability.
Insightful Tips there. Please can I get this .htaccess tricks as an ebook? Thank you.