Enabling Gzip Compression For ASP.NET Core Websites In NGINX

We all want fast sites, right? One step to achieve this is setting up your web server to serve its assets compressed as opposed to uncompressed. This will greatly aid in reducing the size of the files your server is sending across the wire, effectively decreasing the load time for your clients.

ASP.NET Core & Gzip on IIS

Last week I posted a blog titled Developing A .NET Core Site In Windows and Deploying It To A Budget Linux Host. In it, I outlined the steps I took to move Pioneer Code from an IIS hosting service to a Linux host ( DigitalOcean). Prior to making the hosting service switch, I was enabling Gzip by providing a web.config file with the following configuration.

One big problem though, the concept of web.config is platform specific. Meaning web.config only works in IIS. NGINX has not concept of it.

Enabling Gzip in NGINX

NGINX by default only compresses HTML files. This can be demonstrated by opening up chrome and checking the headers in of a fresh NGINX server.

HTML Request

Gzip enabled

Non-HTML Request

Gzip not enabled

As you can see in the HTML Request we see Content-Encoding: gzip in the response header and in the Non-HTML Request we don't.

First things first, SSH into your server. Once connected, follow these steps...

1: Open NGINX the config file

SSH into your machine and open the NGINX config file in the editor of your choice. I currently have been using nano, but any editor will work fine.

sudo nano /etc/nginx/nginx.conf

2: Update your config

There are plenty of settings inside this config file. I would highly recommend reading up more about them at, Nginx Gzip Configuration.

That being said, the following is what I am currently using. In your config file, locate the section titled "Gzip Settings" to compare.

# Gzip Settings
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_min_length 256;

It is worth noting that the specific section in configuration that tells NGINX to compress assets types other then HTML is gzip_types. As you can see, we have to explicitly add mime types we want to include.

Save your configuration once you are done. In nano, we do this by hitting ctrl+x, then y and finally enter.

3: Restart NGINX

To get NGINX to take this new configuration into play, we need to restart the NGINX services.

sudo service nginx restart


At this point when you view response headers of non-HTML assets inside Chrome dev tools, you should now see the appropriate Content-Encoding header being set.

Non-Html asset zipped

That is it! Your clients will thank you and Google will have one less reason to penalize you.