The .htaccess
file is a powerful configuration file used on web servers running the Apache Web Server software. It allows you to control many aspects of your website's behavior. Here are some common and useful configurations you can achieve with an .htaccess
file:
1. Redirects
301 Redirect (Permanent)
Redirect 301 /old-page.html http://www.example.com/new-page.html
302 Redirect (Temporary)
Redirect 302 /old-page.html http://www.example.com/new-page.html
Redirect Entire Site to a New Domain
RewriteEngine On
RewriteCond %{HTTP_HOST} ^old-domain.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www.old-domain.com [NC]
RewriteRule ^(.*)$ http://new-domain.com/$1 [L,R=301,NC]
2. Rewriting URLs
Enable URL Rewriting
RewriteEngine On
Simple Rewrite Rule
RewriteRule ^old-page.html$ new-page.html [L,R=301]
Rewrite with Query Strings
RewriteRule ^products/([0-9]+)/?$ product-details.php?id=$1 [L]
3. Security
Deny Access to .htaccess
<Files .htaccess>
Order allow,deny
Deny from all
</Files>
Block Visitors by IP Address
Order Deny,Allow
Deny from 123.456.789.000
Allow from all
Password Protection
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /path/to/.htpasswd
Require valid-user
Create the .htpasswd
file using the htpasswd
utility.
4. Custom Error Pages
Custom Error Documents
ErrorDocument 404 /errors/404.html
ErrorDocument 500 /errors/500.html
5. Directory Indexes
Specify Custom Directory Index
DirectoryIndex index.html index.php
Disable Directory Listing
Options -Indexes
6. Caching
Enable Browser Caching
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 2 days"
</IfModule>
7. Gzip Compression
Enable Gzip Compression
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/x-javascript application/json
</IfModule>
8. Set MIME Types
Add MIME Types
AddType application/x-httpd-php .html .htm
AddType video/mp4 .mp4
9. Hotlink Protection
Prevent Hotlinking
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [F]
10. Force HTTPS
Redirect HTTP to HTTPS
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Putting it All Together
You can combine multiple configurations in a single .htaccess
file. Just be sure to test your .htaccess
file thoroughly, as incorrect configurations can lead to server errors.
Example file: htaccess example file.zip