htaccessapacheserver configurationseosecurity
The Complete Guide to .htaccess
Master the .htaccess file - redirects, rewrites, security rules, caching, and common configurations explained.
June 20, 2024ยท8 min read
What is .htaccess?
.htaccess (hypertext access) is a configuration file for Apache web servers. It allows per-directory configuration without editing the main server config.
Common .htaccess Configurations
Force HTTPS
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Remove www
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1%{REQUEST_URI} [L,R=301]
Custom 404 page
ErrorDocument 404 /404.html
ErrorDocument 500 /500.html
Enable GZIP compression
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>
Browser caching
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
</IfModule>
Block bad bots
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} (BadBot|SomeSpammer) [NC]
RewriteRule .* - [F,L]
Disable directory listing
Options -Indexes
.htaccess Performance
Note: .htaccess is parsed on every request. For high-traffic sites, prefer editing the main Apache config (httpd.conf) directly.
Generate your .htaccess with our .htaccess Generator.