How to enable Gzip compression on apache and Nginx

What is gzip compression?

Website gzip compression help to reduce webpage size and any other files like css, js, web fonts and images etc.

How it affect website speed?

Gzip compression compress the file to around 30% of page size, before it get served to client browser, and then browser uncompressed the same.

As we know larger the file more time it will take to load, now as gzip compress compress the files before it get served to browser, leads to reduce page size and that’s why it affect the website speed.

How to enable gzip compression on Apache?

To enable gzip compression apache you need to add following lines to you website htaccess file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<IfModule mod_deflate.c>
  # Compress HTML, CSS, JavaScript, Text, XML and fonts
  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>

How to enable gzip compression on nginx

To enable gzip compression on nginx is not like Apache, we need to edit website configuration file for nginx. It usually exists under /etc/nginx/sites-available/ directory. The code looks like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
server{
	listen:80
	........
 
	gzip on;
	gzip_disable "msie6";
 
	gzip_vary on;
	gzip_proxied any;
	gzip_comp_level 6;
	gzip_buffers 16 8k;
	gzip_http_version 1.1;
	gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
	location /{
	.......
	}
 
	.....
}

After making changes we need to restart nginx using below command

sudo /etc/init.d/nginx restart

or

sudo service nginx restart

Leave a Reply

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

*