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
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
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.
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
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.
That is it! Your clients will thank you and Google will have one less reason to penalize you.