We will build NGINX with the 3rd party Google PageSpeed Optimization Library (ngx_pagespeed) which will automatically scan our HTML and CSS on page load and then inline our critical styles for us on subsequent requests.

This article assumes you’ve got an Ubuntu 16.04 (Xenial) server and a server rendered React (or any other JS framework) application ready to be served through NGINX. It also assumes you know how to reverse proxy a node server through NGINX. If you’re looking for a guide on how to set up server rendering with React you can read this article first;

https://hackernoon.com/hot-reload-all-the-things-ec0fed8ab0

Install “vanilla” NGINX

Sign in to your Ubuntu server and add the NGINX source package from Launchpad;

sudo add-apt-repository -y ppa:nginx/stable

Then we have to update apt to include our new source.

sudo apt-get update

And finally we install NGINX;

sudo apt-get install -y nginx

You should now be able to hit your server and see the default NGINX landing page (if not, try running service nginx start) .

Great, we now have NGINX up and running! Let’s get to the fun part. Now we’re going to rebuild our NGINX installation from source and bundle in ngx_pagespeed, the NGINX version of Google’s mod_pagespeed.

First, let’s stop our running NGINX instance;

service nginx stop

Getting the ngx_pagespeed module

First, lets grab some dependencies we’re going to need;

sudo apt-get install build-essential zlib1g-dev libpcre3 libpcre3-dev unzip

Then lets make a folder for ngx_pagespeed;

mkdir /opt/pagespeed && cd /opt/pagespeed

Then we download it;

And finally unzip and cd into the folder;

sudo unzip latest-beta.zip && cd ngx_pagespeed-latest-beta

Now we have to get the PageSpeed Optimization Library itself;

Let’s unpackage this as well;

sudo tar -xzvf 1.12.34.2-x64.tar.gz

We now have our PageSpeed module downloaded and ready to be built into NGINX. So let’s get on that!

Building NGINX from source

Let’s open our apt sources for NGINX, we have to make sure we get the include the sources for our NGINX package so we can customise our build;

Open and uncomment the deb-src link from this file;

sudo vi /etc/apt/sources.list.d/nginx-ubuntu-stable-xenial.list

The file should look like this (depending on your version, it should say trusty if you’re on Ubuntu 14.04);