[apache] How can I get Apache gzip compression to work?

I can't get my site to use gzip compression.

I recently watched this video by Chris Coyier over at css-tricks.com. In the video, he talks about enabling gzip compression to make websites run faster.

As per his instruction, I linked through to github via html5boilerplate.com, copied the gzip compression code from their .htaccess file, pasted it into my own, and uploaded it to my site.

I've tested it via gzipwtf.com and it doesn't seem to work. Can anyone help me with this?

My .htaccess file looks like this:

# ----------------------------------------------------------------------
# Trim www
# ----------------------------------------------------------------------

RewriteEngine On
RewriteCond %{HTTP_HOST} !^orbitprint.com$ [NC]
RewriteRule ^(.*)$ http://orbitprint.com/$1 [L,R=301]

# ----------------------------------------------------------------------
# Gzip compression
# ----------------------------------------------------------------------

<IfModule mod_deflate.c>

  # Force deflate for mangled headers developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping/
  <IfModule mod_setenvif.c>
    <IfModule mod_headers.c>
      SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
      RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
    </IfModule>
  </IfModule>

  # Compress all output labeled with one of the following MIME-types
  <IfModule mod_filter.c>
    AddOutputFilterByType DEFLATE application/atom+xml \
                                  application/javascript \
                                  application/json \
                                  application/rss+xml \
                                  application/vnd.ms-fontobject \
                                  application/x-font-ttf \
                                  application/xhtml+xml \
                                  application/xml \
                                  font/opentype \
                                  image/svg+xml \
                                  image/x-icon \
                                  text/css \
                                  text/html \
                                  text/plain \
                                  text/x-component \
                                  text/xml
  </IfModule>

</IfModule>

This question is related to apache .htaccess gzip mod-deflate

The answer is


In my case i have used following code for enabling gzip compression in apache web server.

  # Compress HTML File, CSS File, JavaScript File, Text File, XML File and Fonts
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/xml
    AddOutputFilterByType DEFLATE application/json
    AddOutputFilterByType DEFLATE application/x-httpd-php
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/x-javascript
    AddOutputFilterByType DEFLATE font/otf
    AddOutputFilterByType DEFLATE font/ttf

I have taken reference from http://www.tutsway.com/enable-gzip-compression-using-htacess.php.


Ran into this problem using the same .htaccess configuration. I realized that my server was serving javascript files as text/javascript instead of application/javascript. Once I added text/javascript to the AddOutputFilterByType declaration, gzip started working.

As to why javascript was being served as text/javascript: there was an AddType 'text/javascript' js declaration at the top of my root .htaccess file. After removing it (it had been added in error), javascript starting serving as application/javascript.


Enable compression via .htaccess

For most people reading this, compression is enabled by adding some code to a file called .htaccess on their web host/server. This means going to the file manager (or wherever you go to add or upload files) on your webhost.

The .htaccess file controls many important things for your site.

The code below should be added to your .htaccess file...

<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

Save the .htaccess file and then refresh your webpage.

Check to see if your compression is working using the Gzip compression tool.


If your Web Host is through C Panel Enable G ZIP Compression on Apache C Panel

Go to CPanel and check for software tab.

Previously Optimize website used to work but now a new option is available i.e "MultiPHP INI Editor".

Select the domain name you want to compress.

Scroll down to bottom until you find zip output compression and enable it.

Now check again for the G ZIP Compression.

You can follow the video tutorial also. https://www.youtube.com/watch?v=o0UDmcpGlZI


<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

<IfModule mod_deflate.c>
# Insert filters
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/x-httpd-php
AddOutputFilterByType DEFLATE application/x-httpd-fastphp
AddOutputFilterByType DEFLATE image/svg+xml

# Drop problematic browsers
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html

# Make sure proxies don't deliver the wrong content
Header append Vary User-Agent env=!dont-vary
</IfModule>

Your .htaccess should run just fine; it depends on four different Apache modules (one per each <IfModule> directive). I guess one of the following:

  • your Apache server doesn't have either mod_filter, mod_deflate, mod_headers and/or mod_setenvif modules installed and running. If you can access the server config, please check /etc/apache2/httpd.conf (and the related Apache config files); otherwise, you can see which modules are loaded via phpinfo(), under the apache2handler section (see attached image); (EDIT) OR, you can open a terminal window and issue the command sudo apachectl -M that will list the loaded modules;

  • if you get an http 500 internal server error, your server may not be allowed to use .htaccess files;

  • you are trying to load a PHP file that sends its own headers (overwriting Apache'sheaders), thus "confusing" the browser.

In any case, you should double-check your server config and error logs to see what's going wrong. Just to be sure, try to use the fastest way suggested here in Apache docs:

AddOutputFilterByType DEFLATE text/html text/plain text/xml

and then try to load a large textfile (preferably, clean your cache first).

(EDIT) If the needed modules are there (in the Apache modules dir) but aren't loaded, just edit /etc/apache2/httpd.conf and add a LoadModule directive for each one of them.

If the needed modules aren't there (neither loaded, nor in the Apache modules directory), I fear that the only option is reinstalling Apache (a complete version).

phpinfo() apache2handler section


In my case append only this line worked

SetOutputFilter DEFLATE


It is better to implement it as in the snippet below.

Just paste the content below in your .htaccess file, then, check the performance using: Google PageSpeed, Pingdom Tools and GTmetrics.

# Enable GZIP
<ifmodule mod_deflate.c>
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
</ifmodule>

# Expires Headers - 2678400s = 31 days
<ifmodule mod_expires.c>
  ExpiresActive On
  ExpiresDefault "access plus 1 seconds"
  ExpiresByType text/html "access plus 7200 seconds"
  ExpiresByType image/gif "access plus 2678400 seconds"
  ExpiresByType image/jpeg "access plus 2678400 seconds"
  ExpiresByType image/png "access plus 2678400 seconds"
  ExpiresByType text/css "access plus 518400 seconds"
  ExpiresByType text/javascript "access plus 2678400 seconds"
  ExpiresByType application/x-javascript "access plus 2678400 seconds"
</ifmodule>

# Cache Headers
<ifmodule mod_headers.c>
  # Cache specified files for 31 days
  <filesmatch "\.(ico|flv|jpg|jpeg|png|gif|css|swf)$">
  Header set Cache-Control "max-age=2678400, public"
  </filesmatch>
  # Cache HTML files for a couple hours
  <filesmatch "\.(html|htm)$">
  Header set Cache-Control "max-age=7200, private, must-revalidate"
  </filesmatch>
  # Cache PDFs for a day
  <filesmatch "\.(pdf)$">
  Header set Cache-Control "max-age=86400, public"
  </filesmatch>
  # Cache Javascripts for 31 days
  <filesmatch "\.(js)$">
  Header set Cache-Control "max-age=2678400, private"
  </filesmatch>
</ifmodule>

First of all go to apache/bin/conf/httpd.conf and make sure that mod_deflate.so is enabled.

Then go to the .htaccess file and add this line:

SetOutputFilter DEFLATE

This should output all the content served as gzipped, i have tried it and it works.


Examples related to apache

Enable PHP Apache2 Switch php versions on commandline ubuntu 16.04 Laravel: PDOException: could not find driver How to deploy a React App on Apache web server Apache POI error loading XSSFWorkbook class How to enable directory listing in apache web server Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details How to enable php7 module in apache? java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is missing while starting Apache server on my computer

Examples related to .htaccess

Use .htaccess to redirect HTTP to HTTPs Getting a 500 Internal Server Error on Laravel 5+ Ubuntu 14.04 Server unable to read htaccess file, denying access to be safe Laravel 5 – Remove Public from URL Laravel 5 not finding css files How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue? How Can I Remove “public/index.php” in the URL Generated Laravel? Apache 2.4 - Request exceeded the limit of 10 internal redirects due to probable configuration error Forbidden You don't have permission to access / on this server Htaccess: add/remove trailing slash from URL

Examples related to gzip

gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now How to unzip gz file using Python How to enable GZIP compression in IIS 7.5 Using GZIP compression with Spring Boot/MVC/JavaConfig with RESTful How are zlib, gzip and zip related? What do they have in common and how are they different? How to uncompress a tar.gz in another directory compression and decompression of string data in java Extract and delete all .gz in a directory- Linux How to extract filename.tar.gz file Read from a gzip file in python

Examples related to mod-deflate

How can I get Apache gzip compression to work?