Optimized .htacces for Cache-Control / Expires / Security

Below codes will optimized website performance and security with:

  • Gzip Compression
  • Strict-Transport-Security
  • unset ETag
  • set X-Content-Type-Options “nosniff
  • Cache-Control for Images (1 month) and CSS/JS with (1 week)
  • Expires for Images (1 month) and CSS/JS with (1 week)

If you are using cPanel, putting these config in pre_main_2.conf is preferred which will apply these to all websites.

<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilterByType DEFLATE image/x-icon
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/xml

<ifModule mod_headers.c>
Header unset ETag
FileETag None
Header append Vary "Accept-Encoding"
<filesMatch ".(ico|jpg|png|gif|webmanifest)$">
Header set Cache-Control "max-age=2592000, public"
<filesMatch ".(js|css)$">
Header set Cache-Control "max-age=604800, public"
Header set X-Content-Type-Options "nosniff"
<filesMatch ".(html|php|txt|xml)$">
Header set Cache-Control "private, must-revalidate"
Header always set Strict-Transport-Security "max-age=31536000; includeSubdomains; preload" env=HTTPS
Header always set X-Xss-Protection "1"
Header set X-Frame-Options sameorigin
Header set Referrer-Policy "no-referrer-when-downgrade"
Header append Vary User-Agent

<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType text/html "access plus 1 seconds"
ExpiresByType text/xml "access plus 1 seconds"
ExpiresByType text/plain "access plus 1 seconds"
ExpiresByType application/xml "access plus 1 seconds"
ExpiresByType application/json "access plus 1 seconds"
ExpiresByType text/css "access plus 1 week"
ExpiresByType text/javascript "access plus 1 week"
ExpiresByType application/javascript "access plus 1 week"
ExpiresByType application/x-javascript "access plus 1 week"
ExpiresByType image/x-ico "access plus 1 year"
ExpiresByType image/x-icon "access plus 1 year"


At https://www.ssllabs.com/ssltest/analyze.html you should get a A+ overall rating

At https://www.giftofspeed.com/cache-checker/ you should see all images with 30 days and all CSS/JS with 7 days

At http://tools.seobook.com/server-header-checker/ you should see all images with Expires at 30 days and all CSS/JS with Expires at 7 days.

At https://www.giftofspeed.com/gzip-test/ you should see “GZIP is Enabled”

Leave a Reply

Your email address will not be published. Required fields are marked *