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

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


%d bloggers like this: