How to Install Nginx with PageSpeed on Ubuntu 20.04 LTS

The Google PageSpeed module, also known as mod_PageSpeed, is an open-source Apache HTTP or Nginx server-level package with modules that helps optimize your site using various filters to pages that optimize server stylesheets, JavaScript, and HTML files and images through caching and rewriting among the top features.

The following tutorial will teach you how to install Nginx with Google Pagespeed on Ubuntu 20.04 LTS Focal Fossa with optimal setups to increase your website speed server-side.

Update Ubuntu

First, update your system to ensure all packages are up-to-date to avoid conflicts while installing the Pagespeed module.

sudo apt update && sudo apt upgrade -y

Install Required Packages

Use the following command to install or check if the packages are installed.

sudo apt install apt-transport-https unzip wget curl git dpkg-dev uuid-dev make build-essential gnupg2 git ca-certificates lsb-release ca-certificates lsb-release software-properties-common -y

Install Latest Nginx Mainline or Stable

For pagespeed, you will need to compile the Nginx source but given you are trying to improve your site speed, it is highly recommended to import and install the latest Nginx version available between mainline or stable.

Nginx recommends using the mainline version, but the stable is just as suitable for users that do not want to upgrade as much.


Import GPG Key

sudo wget -O- | gpg --dearmor | sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg
echo deb [arch=amd64,arm64 signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] `lsb_release -cs` nginx | sudo tee /etc/apt/sources.list.d/nginx-mainline.list

Option 2 – Import Nginx Stable

echo deb [arch=amd64,arm64 signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] `lsb_release -cs` nginx | sudo tee /etc/apt/sources.list.d/nginx-stable.list

Next, run an update apt update to sync.

sudo apt update

Now begin installing Nginx; the tutorial will install Nginx mainline.

sudo apt install nginx

Active the service using the following command.

sudo systemctl enable nginx --now

Download Nginx Source Package

You will need to compile the ngx_pagespeed module from the source as a dynamic module. If you have not done this before, we will cover how to create a directory for you to compile for this module today and in the future. Every time you update your Nginx through the APT package manager, you must re-download the source and re-compile the dynamic modules.

First, by default, the deb-src repository is not added and enabled. This must be imported and added before you can download the Nginx source, or it will grab the wrong version.

echo deb-src [arch=amd64,arm64 signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] `lsb_release -cs` nginx | sudo tee -a /etc/apt/sources.list.d/nginx-mainline.list

Option 2 – Nginx Stable Deb-Source

echo deb-src [arch=amd64,arm64 signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] `lsb_release -cs` nginx | sudo tee -a /etc/apt/sources.list.d/nginx-stable.list

Next, run an APT update to sync the new addition.

sudo apt update

Create the Nginx source directory.

sudo mkdir -p /usr/local/src/nginx

Now go to your newly created directory by CD.

cd /usr/local/src/nginx

Next, download the Nginx source package as per the below sudo command.

sudo apt source nginx


Note you will see a denied message. This can be ignored.

Next, type the following command to confirm the source has been downloaded.

ls -l

The output should be, for example.

How to Install Nginx with Google PageSpeed on Ubuntu 20.04 LTS

Clone ngx_pagespeed Repository

In the next part of the guide, you will need to download the ngx_pagespeed” source package. It is recommended to clone the pagespeed source using Git, as you can easily pull updates later on and re-compile in the future.

In this part, you have two options currently v1.13.35.2-stable repository branch or the v1.14.33.1-RC1 pre-release branch. Both now have issues. A suggestion would be to visit Git and read the list of the current issues to see if any would affect you more than the other.

The tutorial found installing the pre-release version worked best. Although stable may benefit you more, it’s a tough call.

First, CD into the directory:

cd /usr/local/src

Now clone the ngx_pagespeed git source:

sudo git clone

The next part can be done in two ways, stable or pre-release. Both will be listed below.

Option 1. Download Stable ngx_pagespeed

CD into the newly cloned ngx_pagespeed source, and check out the latest stable branch.

cd /usr/local/src/incubator-pagespeed-ngx

Check out the latest-stable pagespeed release.

sudo git checkout latest-stable

Example output:

Now, you would have noticed that the end of the output PSOL_BINARY_URL is printed out. The PSOL URL download link is the pagespeed optimization libraries that need to be downloaded from the branch you used, the GIT checkout.

To find the URL of the libraries to download, type the following command to reveal.

Use the cat command to find the URL.


Example output:$BIT_SIZE_NAME.tar.gz

Note the output has $BIT_SIZE_NAME. This for, most people will be x64.

Next, download the PageSpeed Optimization Libraries (PSOL) to proceed.

sudo wget

Now extract the archive. This will create a psol directory automatically and extract the files. You will get a long list printout, but all the libraries are ready to be compiled as a dynamic module with your Nginx source.

sudo tar xvf

Option 2. Download Pre-Release ngx_pagespeed

Using the pre-release ngx_pagespeed module and PSOL libraries remains the same as the stable branch. So all you will be doing is changing some options as per below.

CD into the clone ngx_pagespeed source, and check out the latest pre-release branch. Note the pre-release branch will most likely change in the future. 

Therefore, you should visit the Github project branches and find the latest one. Currently, the 36 branch is the pre-release branch with v1.14.33.1-RC1. We will skip the step about cloning and refer back to the “stable” for instructions.

cd /usr/local/src/incubator-pagespeed-ngx

Check out the pre-release pagespeed branch numbered 36:

sudo git checkout 36

Now, you would have noticed that the end of the output PSOL_BINARY_URL is printed out. The PSOL URL download link is the pagespeed optimization libraries that need to be downloaded from the branch you used, the GIT checkout.

To find the URL of the libraries to download, type the following command to reveal.


Example output:$BIT_SIZE_NAME.tar.gz

Note the output has $BIT_SIZE_NAME. This for, most people will be x64.

Next, download the PageSpeed Optimization Libraries (PSOL) to proceed.


Extract the archives.

sudo tar xvf psol- 

Compile Nginx with ngx_pagespeed Module

Next, you will compile the Nginx source you downloaded with the ngx_pagespeed module you downloaded with the PSOL libraries.

First, CD to your Nginx source directory. Note the Nginx version number may be different.

Example only:

cd /usr/local/src/nginx/nginx-{version}

Replace {version} with your Nginx version, as everyone’s will be different.

Next, install build dependencies for the Nginx source.

sudo apt build-dep nginx -y

Now you will compile the ngx_pagespeed module with the –with-compact flag. This process will make the future file module compatible with your active Nginx server.

sudo ./configure --with-compat --add-dynamic-module=/usr/local/src/incubator-pagespeed-ngx

Next, use the make the modules command. This process will go for about 1 minute at most.

sudo make modules

Now, copy the newly made” module to your active Nginx server directory. The locations vary depending on your installation, but most people should be the same.

sudo cp objs/ /etc/nginx/modules/

Alternative for users that may have Nginx located elsewhere:

sudo cp objs/ /usr/share/nginx/modules/

Load ngx_pagespeed Module in Nginx

Now the time has come to load the ngx_pagespeed module in Nginx by opening your nginx.conf file.

sudo nano /etc/nginx/nginx.conf

Now, add the following line.

 load_module modules/;


To finish off, test your Nginx configuration in the dry run command and restart the Nginx server if ok.

sudo nginx -t

Example out:

 nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
 nginx: configuration file /etc/nginx/nginx.conf test is successful

If the Nginx syntax is ok, restart the Nginx service:

sudo systemctl restart nginx

Create PageSpeed Cache

Before configuring your filters, you must create a cache directory for Nginx pagespeed to store the cached files and image conversions. This can be changed to your chosen location; however, we will make it under the Nginx folder for the guide.

Create the cache directory.

sudo mkdir -p /etc/nginx/ngx_pagespeed_cache

Set www-data user as the owner (important).

sudo chown -R www-data:www-data /etc/nginx/ngx_pagespeed_cache

PageSpeed Filers Set Up

There are a few ways to set up your pagespeed filters, but none are right or wrong. However, the example will create a pagespeed.conf” configuration file for this tutorial, as it’s easier to modify the settings than placing it in the server block as this can overgrow, another tip I would use Git to monitor the changes and restore soon as you will need to modify the files extensively and constantly.

Another benefit of using a configuration file for the pagespeed configuration is that it can be tricky and often break a website. If you want to revert the pagespeed modules quickly, you can comment against the include pagespeed.conf line in your server block.

Create the pagespeed.conf file.

sudo nano /etc/nginx/pagespeed.conf

Next, you must review the primary filter setup. This is an example only, and you must tweak the settings to match, at the end of the tutorial links to resources to explain in-depth every setting would be a good place to start for users new to the pagespeed module.

Example only:

###enable pagespeed on the server block###
 pagespeed on;
 pagespeed Domain;
 pagespeed Domain;

###Add this line if your website runs on HTTPS###
 pagespeed FetchHttps enable;

###Set up admin location###
 admin console
 pagespeed Statistics on;
 pagespeed StatisticsLogging on;
 pagespeed StatisticsLoggingIntervalMs 60000;
 pagespeed StatisticsLoggingMaxFileSizeKb 1024;
 pagespeed MessageBufferSize 100000;
 pagespeed LogDir /var/log/pagespeed;
 pagespeed AdminPath /pagespeed_admin;

###Specify the file cache folder that you created earlier###
 pagespeed FileCachePath /etc/nginx/ngx_pagespeed_cache;

###Set the cache settings, you can play around with these numbers###
 pagespeed FileCacheSizeKb            102400;
 pagespeed FileCacheCleanIntervalMs   3600000;
 pagespeed FileCacheInodeLimit        500000;
 pagespeed LRUCacheKbPerProcess     1024;
 pagespeed LRUCacheByteLimit        16384;

###OPTIONAL: use Memcached to further increase performance of pagespeed###
 pagespeed MemcachedThreads 1;
 pagespeed MemcachedServers "localhost:11211";

###Ensure requests for pagespeed optimized resources go to the pagespeed handler###
 and no extraneous headers get set.
 location ~ ".pagespeed.([a-z].)?[a-z]{2}.[^.]{10}.[^.]+" {
   add_header "" "";
 location ~ "^/pagespeed_static/" { }
 location ~ "^/ngx_pagespeed_beacon$" { }

###Set the most common safe filters###
 pagespeed RewriteLevel CoreFilters;

 location ~ ^/pagespeed_admin {
    allow your-own-IP-address;
    deny all;

Now, you may have noticed we renamed in the newly created pagespeed directory the setup file” This was done as if you host multiple websites on the same server. Some may need different pagespeed customization, so separating setup files will keep your setup from getting messy.

The set filter option was “CoreFilters” as the re-write level. Overall, PageSpeed offers three re-write levels: “CoreFilters, PassThrough, and OptimizeForBandwidth”. As you may have noticed by the original comments, “CoreFilters” is safe for most websites and is used as the default for testing.

Corefilters consists of:

  •   add_head – Adds a <head> element to the document if not already present.
  •   combine_css – Combines multiple CSS elements into one.
  •   combine_javascript – Combines multiple script elements into one.
  •   convert_meta_tags – Adds a response header for each meta tag with an http-equiv attribute.
  •   extend_cache – Extends cache lifetime of CSS, JS, and image resources that have not been optimized by signing URLs with a content hash.
  •   fallback_rewrite_css_urls – Rewrites resources referenced in any CSS file that cannot otherwise be parsed and minified.
  •   flatten_css_imports – Inline CSS by flattening all @import rules.
  •   inline_css – Inlines small CSS files into the HTML document.
  •   inline_import_to_link – Inlines <style> tags comprising only CSS @imports by converting them to equivalent <link> tags.
  •   inline_javascript – Inlines small JS files into the HTML document.
  •   rewrite_css – Rewrites CSS files to remove excess whitespace and comments, and, if enabled, rewrite or cache-extend images referenced in CSS files. In OptimizeForBandwidth mode, the minification occurs in-place without changing URLs.
  •   rewrite_images – Optimizes images, re-encoding them, removing excess pixels, and inlining small images. In OptimizeForBandwidth mode, the minification occurs in-place without changing URLs. 
  •   rewrite_javascript – Rewrites JavaScript files to remove excess whitespace and comments. In OptimizeForBandwidth mode, the minification occurs in-place without changing URLs. 
  •   rewrite_style_attributes_with_url – Rewrite the CSS in style attributes if it contains the text ‘url(‘ by applying the configured rewrite_css filter to it.

Now, you can increase CoreFilters further by adding even more filters. However, I would advise doing some research as more filters equal more risk of your website breaking. It’s a fine art to use google pagespeed. For example, below of some additional options.

Remember, this is just an example!! This will takes countless hours of testing for your website, especially if you are new to using the Pagespeed module! My advice, use the core. That does not work; add the settings one by one. Monitor and watch out for website breakages, especially around minifying and combines. The end of the tutorial also has some links that may help.

###css optimization filters###
 pagespeed EnableFilters outline_css;
 pagespeed EnableFilters inline_google_font_css;
 pagespeed EnableFilters move_css_above_scripts;
 pagespeed EnableFilters move_css_to_head;
 pagespeed EnableFilters prioritize_critical_css;

###html optimization filters###
 pagespeed EnableFilters combine_heads;
 pagespeed EnableFilters collapse_whitespace;
 pagespeed EnableFilters convert_meta_tags;
 pagespeed EnableFilters elide_attributes;
 pagespeed EnableFilters pedantic;
 pagespeed EnableFilters remove_comments;
 pagespeed EnableFilters remove_quotes;
 pagespeed EnableFilters trim_urls;

###javascript optimization filters###
 pagespeed EnableFilters canonicalize_javascript_libraries;
 pagespeed EnableFilters defer_javascript;

###image optimization filters###
 pagespeed EnableFilters dedup_inlined_images;
 pagespeed EnableFilters inline_preview_images;
 pagespeed EnableFilters resize_mobile_images;
 pagespeed EnableFilters lazyload_images;
 pagespeed EnableFilters strip_image_color_profile;
 pagespeed EnableFilters strip_image_meta_data;
 pagespeed EnableFilters jpeg_subsampling;
 pagespeed EnableFilters convert_png_to_jpeg;
 pagespeed EnableFilters resize_rendered_image_dimensions;
 pagespeed EnableFilters insert_image_dimensions;
 pagespeed NoTransformOptimizedImages on;
 pagespeed EnableFilters sprite_images;

Once done, CTRL+O to save, then CTRL +X to exit.

Add the following line, test, and restart once set up is complete to include this in your server block.

sudo nano /etc/nginx/sites-available/

Add the following line to include the filters to your server configuration.

include /etc/nginx/pagespeed.conf;

Test your Nginx server before restarting.

sudo nginx -t

If your Nginx syntax is ok and there are no errors, restart the Nginx service:

sudo systemctl restart nginx

WebP Conversion Support

Nginx will require PHP support to convert webp images, and Ubuntu ships with PHP 8.1 by default. However, you may want to use different versions of PHP, so first, import the PHP repository PPA.

sudo add-apt-repository ppa:ondrej/php -y

Next, run an APT update to sync the newly added PPA.

sudo apt update

Now install one of the following packages.

PHP 7.4 WebP Support:

sudo apt install imagemagick php7.4-imagick ffmpeg

PHP 8.0 WebP Support:

sudo apt install imagemagick php8.0-imagick ffmpeg

PHP 8.1 WebP Support:

sudo apt install imagemagick php8.1-imagick ffmpeg

Verify ngx_pagespeed is Operational

The hard work has paid off. Now you want to see if PageSpeed is working, which can be done using the curl command, as in the example below.

curl -I -p

You should see in the output this part as follow.


Preload ngx_pagespeed

The ngx_pagespeed module does not have a preload function, which can be frustrating since it can take several visits before items are adequately cached and optimized. This can be made worse if you had to purge the cache a few times a day, unacceptably leaving your website optimization levels.

Use the following command beload, which will load your preload your website, and this should not be done on shared or lower-end VPS servers, as it can strain your server.

Visit the if you need help creating cron timings.

Preload pagespeed:

sudo wget -m -p -E -k -P /tmp/preload/

Cronjob job one hourly:

00 */1 * * * wget -m -p -E -k -P /tmp/preload/

For those new to Linux and Ubuntu, use the following command to open Cron.

sudo crontab -e

Community Resources for PageSpeed

Comments and Conclusion

PageSpeed is an excellent way of optimizing your website in these times where SEO optimization with Google Search counts on speed more these days than in the previous years.

The software is fantastic as it works on the backend and is not an additional plugin that works through a web application like WordPress. However, PageSpeed can be very complicated; it will most likely take you a few days to even a few weeks to get the optimal setup for your website.

Before you start messing around with filters, visit the Google PageSpeed documentation. It will give you in-depth answers on the risk involved and more about what each filter will potentially do to your website. Most people give up using PageSpeed since they cannot make an effort to get it right, as it’s very time-consuming and frustrating. But if you do, it can transform your website two to 10 times quicker.

Share to...