Use Nginx to serve static React site with gzip and HTTP2

Let's start with pre-compressing our React app when we run the build process. To do this, install a npm package.

      npm install compress-create-react-app --save-dev

Then, change the build script in package.json to below.

      build": "react-scripts build && compress-cra"

Whenever we run npm run build, our project will be built and compressed files will be created automatically.

Next, to serve our static files with gzip and HTTP2 using Nginx, we will need to check if we have the modules needed. The modules required are "ngx_http_gzip_static_module" and "ngx_http_v2_module". Run the following command and check if the output contains "--with-http_gzip_static_module" and "--with-http_v2_module".

      sudo nginx -V

Here is the server block of our Nginx configuration that enables gzip and HTTP2. Note that to use HTTP2, we will first need HTTPS. If HTTPS is not yet activated, follow the guide of Let's Encrypt.

      server {
        listen 443 ssl http2;
        ssl_certificate /PATH/TO/YOUR/CERTIFICATE;
        ssl_certificate_key /PATH/TO/YOUR/CERTIFICATE/KEY;
        location / {
          alias /PATH/TO/YOUR/BUILD/FOLDER;
          gzip_static on;
        server_name YOURSERVERNAME;

The gzip_static directive allows Nginx to serve files with .gz extensions, while the http2 activates the support for HTTP2.

weird-cat weird-cat