WP-Mix

A fresh mix of code snippets and tutorials

.htaccess enable compression

Two quick code snippets for compressing your file output with Apache’s mod_deflate (gzip). Compressing your content is a great way to improve performance by decreasing the amount of data that is sent to the client.

To compress all of the file types included in the following code, add the snippet to your site’s root .htaccess file:

<IfModule mod_deflate.c>
	AddOutputFilterByType DEFLATE image/svg+xml image/x-icon
	AddOutputFilterByType DEFLATE application/vnd.ms-fontobject application/x-font-ttf font/opentype
	AddOutputFilterByType DEFLATE application/javascript application/x-javascript text/javascript text/x-js
	AddOutputFilterByType DEFLATE text/html text/plain text/richtext text/css application/json text/xsd text/xsl
	AddOutputFilterByType DEFLATE text/xml text/x-component application/xml application/xhtml+xml application/rss+xml application/atom+xml
</IfModule>

Feel free to add more file types or remove any that are not required.

Alternate version

Here is an alternate version that is better suited if your site needs to accommodate older browsers (like if you’re working on a company Intranet or similar):

<IfModule mod_deflate.c>
	SetOutputFilter DEFLATE
	AddOutputFilterByType DEFLATE image/svg+xml image/x-icon
	AddOutputFilterByType DEFLATE application/vnd.ms-fontobject application/x-font-ttf font/opentype
	AddOutputFilterByType DEFLATE application/javascript application/x-javascript text/javascript text/x-js
	AddOutputFilterByType DEFLATE text/html text/plain text/richtext text/css application/json text/xsd text/xsl
	AddOutputFilterByType DEFLATE text/xml text/x-component application/xml application/xhtml+xml application/rss+xml application/atom+xml
	BrowserMatch ^Mozilla/4 gzip-only-text/html
	BrowserMatch ^Mozilla/4\.0[678] no-gzip
	BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
	SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
	Header append Vary User-Agent env=!dont-vary
</IfModule>

As before, you can add/edit/remove any file types as needed. The code itself enables compression for the specified files unless the browser is older Firefox or IE. Good times.

Update: note that AddOutputFilterByType is now deprecated by newer versions of Apache. Check for support and then make a note to use mod_filter for future projects.

Further Reading

Learn more

.htaccess made easy