How to serve webpack gzipped file in production using nginx.

Image for post
Image for post
Webpack + Gzip + Nginx

If you are building a webapp that uses webpack bundler optimizing site compression is a so simple, gzip is effective way to save bandwidth and speed up your site.😎

Check the current bundle size of your app and review.For example i have compared a simple app with before and after compression.

After gziping app’s size from 277KB to just ~91.2KB!🤔

Instead of generating bundle.js, generate bundle.js.gz using Webpack’s compression plugin.

After enabling build the app two files with bundle.js and bundle.js.gz will be generated.Keep the two files and copy all your bundled app to nginx root folder var/etc/www

But nginx will not picking compressed file by default will serve uncompressed js files.To enable compression, include the gzip directive with the on parameter.

Configuring Nginx’s gzip Settings 👋

Open /etc/nginx/conf.d provide below configuration .

To send a compressed version of a file to the client instead of the regular one, set the gzip_staticdirective to on within the appropriate context.

In this case, to service a request for /path/to/bundle.js, NGINX tries to find and send the file /path/to/bundle.js.gz. If the file doesn’t exist, or the client does not support gzip, NGINX sends the uncompressed version of the file.

Note that the gzip_static directive does not enable on-the-fly compression. It merely uses a file compressed beforehand by any compression tool. To compress content (and not only static content) at runtime, use the gzip directive.

Save and close the file to exit.

To enable the new configuration, restart Nginx.

How to Verify Your Compression☝️

We can test this just like above checking in Network tab, by using curl on each of the test files and examining the output for the Content-Encoding: gzip header.

Now all out bundle should stay uncompressed. you should be able to find Content-Encoding: gzip header in the output.

If that is the case, you have configured gzip compression in Nginx successfully!👏👏👏


Changing Nginx configuration to fully use gzip compression is easy, but the benefits can be immense. Users with limited bandwidth also receive the site faster. Speed is gaining traction as an important part of modern web and using gzip is one big step to improve it.

I try to learn and help others by sharing what I find | |

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store