Optimizing Sites with the .htaccess File

Slow websites suck. Luckily, there are some quick optimizations via the .htaccess file that will improve a site’s loading time and boost your speed score. This is a good opportunity to increase the site’s security too. The key elements the method below addresses:

• Force HTTPS – This requires that you have an active SSL Certificate on your domain (Let’s Encrypt is a good free option) and forces all requests to use HTTPS for stronger encryption

• Accept-Encoding – This tells the browser whether or not the client can handle compressed versions of the content

• Expires Caching – This sets the time duration files will stay cached on visitor’s browsers, so when they revisit the site it loads much faster

• Gzip Compression – This compresses the website files reducing the overall size of the site

# FORCE HTTPS
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# ACCEPT-ENCODING
<IfModule mod_headers.c>
<FilesMatch ".(js|css|xml|png|gz|html|woff2|slim.min.js)$">
Header append Vary: Accept-Encoding
</FilesMatch>
</IfModule>

# EXPIRES CACHING
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 90 days"
ExpiresByType image/jpeg "access plus 90 days"
ExpiresByType image/gif "access plus 90 days"
ExpiresByType image/png "access plus 90 days"
ExpiresByType image/svg "access plus 90 days"
ExpiresByType image/x-icon "access plus 90 days"
ExpiresByType video/mp4 "access plus 90 days"
ExpiresByType video/mpeg "access plus 90 days"
ExpiresByType text/css "access plus 1 week"
ExpiresByType text/javascript "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType application/x-javascript "access plus 1 month"
ExpiresByType application/pdf "access plus 90 days"
ExpiresDefault "access plus 1 week"
</IfModule>

# GZIP COMPRESSION
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
AddOutputFilterByType DEFLATE application/x-font
AddOutputFilterByType DEFLATE application/x-font-opentype
AddOutputFilterByType DEFLATE application/x-font-otf
AddOutputFilterByType DEFLATE application/x-font-truetype
AddOutputFilterByType DEFLATE application/x-font-ttf
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE font/opentype
AddOutputFilterByType DEFLATE font/otf
AddOutputFilterByType DEFLATE font/ttf
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>