How to Install Nginx Google Pagespeed on Debian 11 Bullseye

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.

In the following tutorial, you will learn how to install and do a basic setup with Nginx Pagespeed on Debian 11 Bullseye.

Update Debian System

Update your Debian operating system to make sure all existing packages are up to date:

sudo apt update && sudo apt upgrade -y

Install Dependecies

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 ca-certificates lsb-release debian-archive-keyring -y

Install Latest Nginx Mainline or Stable

For pagespeed, you will need to compile Nginx source but given you are trying to improve your site speed, and 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 ONLY 1 REPOSITORY, NOT BOTH.

curl -sSL https://packages.sury.org/nginx-mainline/README.txt | sudo bash -x

Option 2 – Import Nginx Stable

curl -sSL https://packages.sury.org/nginx/README.txt | sudo bash -x

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-core nginx-common nginx nginx-full -y

Active the service using the following command.

sudo systemctl enable nginx --now

In the imported repository, you will notice additional modules available in this version, most notably brotli support, which you can install with the following steps below.

Open your nginx.conf configuration file:

nano /etc/nginx/nginx.conf

Now add the additional lines before in the HTTP{} section:

brotli on;
brotli_comp_level 6;
brotli_static on;
brotli_types application/atom+xml application/javascript application/json application/rss+xml
  application/vnd.ms-fontobject application/x-font-opentype application/x-font-truetype
  application/x-font-ttf application/x-javascript application/xhtml+xml application/xml
  font/eot font/opentype font/otf font/truetype image/svg+xml image/vnd.microsoft.icon
  image/x-icon image/x-win-bitmap text/css text/javascript text/plain text/xml;

Next, run Nginx dry run.

sudo nginx -t

The output should be the example below; if not, fix the error you have made and fix it.

Example:

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

Restart Nginx service for changes to be live.

sudo systemctl restart nginx

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 needs to be imported and added before you can download the Nginx source, or it will grab the wrong version.

echo "deb-src https://packages.sury.org/nginx-mainline/ bullseye main
" | sudo tee -a /etc/apt/sources.list.d/nginx-mainline.list

Option 2 – Nginx Stable Deb-Source

echo "deb-src https://packages.sury.org/nginx-mainline/ bullseye main" | sudo tee -a /etc/apt/sources.list.d/nginx.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.

Example:

Install/Enable Nginx PageSpeed Module on Debian 11 Bullseye

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

ls -l

The output should be, for example.

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. However stable may benefit you more, it’s a tough call to make.

First, CD into the directory:

cd /usr/local/src

Now clone the ngx_pagespeed git source:

sudo git clone https://github.com/apache/incubator-pagespeed-ngx.git

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

Option 2. Download Stable ngx_pagespeed

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

cd incubator-pagespeed-ngx

Check out the latest-stable pagespeed release.

sudo git checkout latest-stable

Now, you would have noticed at the end of the output PSOL_BINARY_URL 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:

cat PSOL_BINARY_URL

Example output:

https://dl.google.com/dl/page-speed/psol/1.13.35.2-$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 https://dl.google.com/dl/page-speed/psol/1.13.35.2-x64.tar.gz

Now extract the archive. This will create a psoldirectory 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 once done.

sudo tar xvf 1.13.35.2-x64.tar.gz

Option 2. Download Pre-Release ngx_pagespeed

The process for 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 around as per below.

CD into the clone ngx_pagespeed source, 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 refer back to the “stable” for instructions.

cd incubator-pagespeed-ngx

Check out the pre-release pagespeed branch numbered 36:

sudo git checkout 36

Now, you would have noticed at the end of the outputPSOL_BINARY_URL 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.

cat PSOL_BINARY_URL

Example output:

https://dist.apache.org/repos/dist/release/incubator/pagespeed/1.14.36.1/x64/psol-1.14.36.1-apache-incubating-$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.

wget https://dist.apache.org/repos/dist/release/incubator/pagespeed/1.14.36.1/x64/psol-1.14.36.1-apache-incubating-$BIT_SIZE_NAME.tar.gz

Extract the archives.

sudo tar xvf psol-1.14.36.1-apache-incubating-x64.tar.gz 

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-1.21.4/

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 ngx_pagespeed.so 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 madengx_pagespeed.so” module to your active Nginx server directory. The locations may vary depending on your installation, but most people should be the same.

sudo cp objs/ngx_pagespeed.so /etc/nginx/modules/

Alternative:

sudo cp objs/ngx_pagespeed.so /usr/share/nginx/modules/

Load ngx_pagespeed Module in Nginx

Now the time has come to load the ngx_pagespeed module in Nginx. We will use the text editor nano for this. First, open your nginx.conf file.

sudo nano /etc/nginx/nginx.conf

Now, add the following line.

 load_module modules/ngx_pagespeed.so; ##### insert with other modules ###

Example:

Install/Enable Nginx Google Pagespeed Module on Debian 11 Bullseye

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

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 need to create a cache directory for Nginx pagespeed to store the cached files and image conversions. This can be changed to a location of your choosing; 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

Now, there are a few ways you can go about setting up your pagespeed filters, and none are right or wrong. However, the example will create a pagespeed.conf” configuration file for this tutorial.

The reason for this is due to the fact pagespeed configuration can be tricky and often can 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/modules-available/pagespeed.conf

Next, we will go over the primary filter set up safe for most websites. However, this can be changed and modified to a vast amount of different options in the future, but you will need to research this by visiting the documentation carefully.

###enable pagespeed on the server block###
 pagespeed on;
 pagespeed Domain https://www.example.com;
 pagespeed Domain https://example.com;

###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;

###SECURE THE LOCATION FROM BAD BOTS AND MALICOUS ACTORS###
 location ~ ^/pagespeed_admin {
    allow 127.0.0.1;
    allow your-own-IP-address;
    deny all;
 }


###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;

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

The filter option that was set 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 otherwise 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, example below of some additional options.

###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/example.com.conf

Add the following line to include the filters:

include /etc/nginx/modules-available/pagespeed.conf;

Example:

Install/Enable Nginx Google Pagespeed Module on Debian 11 Bullseye

Alternatively, just symlink it from modules-available to modules-enabled, both options work depending on what you prefer using.

Example:

sudo ln -s /etc/nginx/modules-available/pagespeed.conf /etc/nginx/modules-enabled/pagespeed.conf 

REMEMBER TO ONLY USE ONE METHOD.

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

To generate WebP images, install the following packages on your system.

PHP 7.4 WebP Support:

sudo apt install imagemagick php7.4-imagick ffmpeg

PHP 8.0 WebP Support:

sudo apt install imagemagick php8.1-imagick ffmpeg

PHP 8.1 WebP Support:

sudo apt install imagemagick php8.1-imagick ffmpeg

For those that do not have PHP 8.0 or PHP 8.1, this means you are using Debian’s standard repository. This can be fixed by importing the latest PHP builds using the following command.

curl -sSL https://packages.sury.org/php/README.txt | sudo bash -x

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

sudo apt update

Now re-run those commands as mentioned before. Make sure to adjust any other settings if you did a significant PHP upgrade.

Verify ngx_pagespeed is Operational

The hard work has paid off. Now you want to see if PageSpeed is working. We will do this by using the curl command, as in the example below.

curl -I -p https://www.example.com

You should see in the output this part as follows:

x-page-speed: 1.13.35.2-0

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.

However, you enter the following command to pre-fetch all your web pages if you have ramdisk set up. Also, you can set this on a cronjob for the future to do hourly, daily, or weekly.

Visit the Crontab.guru if you need help creating cron timings.

Preload pagespeed ramdisk set up:

sudo wget -m -p -E -k -P /tmp/preload/ https://www.example.com/

Cronjob job one hourly:

00 */1 * * * wget -m -p -E -k -P /tmp/preload/ https://www.example.com/

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

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 also 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. Do not just load ngx_pagespeed and walk away. Testing needs to be done, and the more filters you add, the higher the risk it may break 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 put in the effort to get it right, as it’s very time-consuming and frustrating. But if you do, then it can potentially transform your website by two to 10 times quicker.



Follow LinuxCapable.com!

Like to get automatic updates? Follow us on one of our social media accounts!