Handy .htaccess Tricks: Redirects, GZIP, and Security
Drop-in snippets you can paste into your Apache .htaccess
to speed up and lock down your site.
redirectsgzipbrotli
cachingHSTShotlink protection
Drop-in snippets you can paste into your Apache .htaccess
to speed up and lock down your site.
# Force HTTPS RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] # Choose ONE canonical host (uncomment one block) # Force non-WWW #RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] #RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L] # Force WWW #RewriteCond %{HTTP_HOST} !^www\. [NC] #RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# Tell browsers to use HTTPS for a year and include subdomains Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
# Enable compression (Brotli if available, else GZIP)BrotliCompressionQuality 5 AddOutputFilterByType BROTLI_COMPRESS text/html text/plain text/xml text/css application/javascript application/json image/svg+xml AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json image/svg+xml
# Cache policy for static files (tune to your deploy strategy)ExpiresActive On ExpiresByType text/css "access plus 30 days" ExpiresByType application/javascript "access plus 30 days" ExpiresByType image/svg+xml "access plus 30 days" ExpiresByType image/webp "access plus 90 days" ExpiresByType image/png "access plus 90 days" ExpiresByType image/jpeg "access plus 90 days" ExpiresDefault "access plus 7 days" # Add strong validatorsHeader set Cache-Control "public, max-age=2592000, immutable"
# Redirect a single old URL Redirect 301 /old-page/ /new-page/ # Redirect an entire directory RedirectMatch 301 ^/old-blog/(.*)$ /blog/$1 # Force trailing slashes for “directory style” URLs RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_URI} !\.[a-zA-Z0-9]{2,5}$ RewriteCond %{REQUEST_URI} !/$ RewriteRule ^ %{REQUEST_URI}/ [R=301,L]
# Replace example.com with your domain(s) RewriteEngine on RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{HTTP_REFERER} !^https?://(www\.)?webvaults\.com/ [NC] RewriteRule \.(jpg|jpeg|png|gif|webp|svg)$ - [F,NC,L]
# Tighten what the browser will do Header set X-Frame-Options "SAMEORIGIN" Header set X-Content-Type-Options "nosniff" Header set Referrer-Policy "strict-origin-when-cross-origin" # Example CSP (customize sources to your site) Header set Content-Security-Policy "default-src 'self'; img-src 'self' data: https:; script-src 'self' https://www.googletagmanager.com https://pagead2.googlesyndication.com; style-src 'self' 'unsafe-inline'; font-src 'self' data:"
# Deny access to env/config filesRequire all denied
Related: Website Security Checklist · Speed Optimization · Backup Strategy