Apache .htaccess Configuration Cheat Sheet
Production Apache .htaccess snippets: force HTTPS, www redirect, Options -Indexes, IP blacklisting, SPA routing, and Gzip compression with 1-click copy.
Redirects & Canonical (4 commands)
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Forces all incoming unencrypted HTTP requests to HTTPS with permanent 301 redirect.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
Redirects www subdomains to apex naked domain (e.g. www.example.com -> example.com).
Redirect 301 /old-page.html /new-page/
Simple mod_alias permanent 301 redirect for retired URLs or changed paths.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.html [L]
Single-Page Application (SPA) fallback routing for React, Vue, and Angular routers.
Security & Headers (4 commands)
Options -Indexes
Disables Apache directory index browsing when no index.html is present in a folder.
<FilesMatch "^\.(env|git|htaccess|sql)">
Require all denied
</FilesMatch>
Blocks public web access to sensitive environment, git, and database configuration files.
Header set X-Content-Type-Options "nosniff"
Header set X-Frame-Options "SAMEORIGIN"
Header set Referrer-Policy "strict-origin-when-cross-origin"
Configures modern security response headers preventing MIME sniffing and clickjacking.
<RequireAll>
Require all granted
Require not ip 192.168.1.100
Require not ip 10.0.0.0/24
</RequireAll>
Denies access from specific malicious IP addresses or whole CIDR subnet ranges.
Performance & Caching (3 commands)
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
</IfModule>
Enables Gzip compression for text, HTML, CSS, JavaScript, and JSON payloads.
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/webp "access plus 1 year"
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
</IfModule>
Configures long-term browser cache expiry headers for static assets.
ErrorDocument 404 /404.html
ErrorDocument 500 /500.html
Directs Apache to serve custom branded error pages on 404 Not Found and 500 Server Error.