How to enable gzip on proxy servers on nginx

I use often Gunicorn as web server for django applications.

Usually I use Apache but I’m starting to use nginx as webserver to serve both the static files and the proxied gunicorn response.

I need to do something like what I’ve done with Apache to compress the response after I received from django since I’ve noticed that in my case compressing it before using @gzip_page decorator is more detrimental to performance than doing it after.

Here an essential mysite.conf to put in /etc/nginx/conf.d.

server {
    listen      80;
    charset     utf-8;
    # max upload size
    client_max_body_size 75M;
    # Enable gzip for proxied requests and static files
    gzip on;
    gzip_proxied any;
    gzip_vary on;
    gzip_http_version 1.1;
    gzip_types application/javascript application/json text/css text/xml;
    gzip_comp_level 4;
    # Serve static files via nginx
    location /media  {
        alias /usr/local/etc/files/mysite/media_root;
    location /static {
        alias /usr/local/etc/files/mysite/static_root;
    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        # Serve dynamic requests via gunicorn on custom port (e.g. 8585)
        # and gzip the response
        if (!-f $request_filename) {
            proxy_pass http://localhost:8585;

In this way, content by Gunicorn is served to nginx and before to send it to client nginx gzip it, here with a compression level of 4 of 9. A compression between 1 and 4 is generally acceptable for any text content, avoiding to stress the CPU too much for a small compression gain.

Even the static files like css and javascript are served compressed for client with HTTP 1.1 support. You can add more type to compress including the mime type on the gzip_types row.

Read also on the same topic: How to enable gzip on proxy servers on Apache



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s