This guide covers the most common and useful .htaccess commands for Apache web servers. Use these snippets as needed for your site configuration, security, redirects, and optimization.
1. Enable Rewrite Engine
RewriteEngine On
2. Redirects
- Redirect HTTP to HTTPS:
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
- Redirect a specific page:
Redirect 301 /oldpage.html /newpage.html
- Redirect entire site:
Redirect 301 / http://newdomain.com/
3. Custom Error Pages
ErrorDocument 400 /400.html
ErrorDocument 401 /401.html
ErrorDocument 403 /403.html
ErrorDocument 404 /404.html
ErrorDocument 500 /500.html
4. Directory Index
DirectoryIndex index.php index.html
5. Prevent Directory Listing
Options -Indexes
6. Deny/Allow Access
- Deny access to a file:
<Files "config.php">
Order allow,deny
Deny from all
</Files>
- Allow only specific IP:
Order deny,allow
Deny from all
Allow from 123.123.123.123
7. Password Protect a Directory
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /full/path/to/.htpasswd
Require valid-user
8. Set Cache-Control Headers
<FilesMatch "\.(jpg|jpeg|png|gif|css|js)$">
Header set Cache-Control "max-age=2592000, public"
</FilesMatch>
9. Block Specific User Agents
SetEnvIfNoCase User-Agent "BadBot" bad_bot
Deny from env=bad_bot
10. Prevent Hotlinking
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?yourdomain.com/ [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [F]
11. Force File Download
<FilesMatch "\.(pdf|mp3)$">
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>
12. Gzip Compression
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript
</IfModule>
13. Set Timezone
SetEnv TZ America/New_York
14. Prevent Image Hotlinking (Alternative)
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?yourdomain.com/ [NC]
RewriteRule \.(gif|jpg|jpeg|png)$ - [F,NC]
15. Restrict Access by Referrer
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?yourdomain.com/ [NC]
RewriteRule .* - [F]
Feel free to copy and adapt these rules for your own .htaccess file. Always test changes to avoid misconfigurations.