Use ngx_pagespeed to Optimize Front-End Pages and Speed Up WordPress

Nginx PageSpeed is an Nginx extension module whose main job is to optimize front-end page output on the server side so the site follows the recommendations from tools such as PageSpeed Insights more closely. Once PageSpeed is in place, front-end developers can hand off a lot of routine optimization work to the server. That does increase server load somewhat, but from the perspective of reducing requests and shrinking transferred assets, the trade-off is often worth it.

The main things ngx_pagespeed can do

ngx_pagespeed covers most of the front-end optimization tasks a typical site needs. Some of the most important and commonly used features include:

  • Image optimization, including removing metadata, resizing, and recompressing images.
  • Compressing, combining, cascading, and inlining CSS and JavaScript so critical CSS can be loaded more efficiently.
  • Inlining small assets, such as tiny images, as base64 content inside the HTML.
  • Delaying image and JavaScript loading so only above-the-fold assets are loaded immediately and scripts can be deferred asynchronously.
  • Rewriting and minifying HTML, such as removing comments and unnecessary whitespace.
  • Increasing cache lifetimes for static resources.

After using ngx_pagespeed, the source site was able to reach a score of 100 in PageSpeed Insights on both mobile and desktop in many cases, which is extremely difficult to achieve through manual front-end tuning alone.

PageSpeed Insights result after using ngx_pagespeed

Install the dependencies needed for ngx_pagespeed

Before installing the module itself, make sure the compilation dependencies are available.

For RedHat, CentOS, or Fedora:

sudo yum install gcc-c++ pcre-devel zlib-devel make unzip

For Ubuntu or Debian:

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

If the dependencies are already installed, you may still need to upgrade them because ngx_pagespeed expects relatively recent compiler versions.

How to install ngx_pagespeed in an LNMP environment

The original environment used the LNMP one-click install script, so the easiest approach was to edit the Nginx upgrade script, add the ngx_pagespeed compile option, and rebuild Nginx. If you do not want to upgrade Nginx itself, you can still rebuild the same version and include the module during that process.

1. First, download PageSpeed according to the official instructions. Save the following commands into a file such as download_pagespeed.sh, run chmod +x download_pagespeed.sh, and then execute ./download_pagespeed.sh to download and extract the module source.

#[check the release notes for the latest version]
NPS_VERSION=1.13.35.2-stable
cd /opt
wget https://github.com/apache/incubator-pagespeed-ngx/archive/v${NPS_VERSION}.zip
unzip v${NPS_VERSION}.zip
nps_dir=$(find . -name "*pagespeed-ngx-${NPS_VERSION}" -type d)
cd "$nps_dir"
NPS_RELEASE_NUMBER=${NPS_VERSION/beta/}
NPS_RELEASE_NUMBER=${NPS_VERSION/stable/}
psol_url=https://dl.google.com/dl/page-speed/psol/${NPS_RELEASE_NUMBER}x64.tar.gz
[ -e scripts/format_binary_url.sh ] && psol_url=$(scripts/format_binary_url.sh PSOL_BINARY_URL)
wget ${psol_url}
tar -xzvf $(basename ${psol_url})  # extracts to psol/

Starting from version 1.12.34, some people ran into problems downloading PSOL through the official script. In that case, PSOL can be downloaded manually from a URL like the one below, replacing the version and architecture as needed.

https://dl.google.com/dl/page-speed/psol/[PageSpeed版本]-x[系统位数].tar.gz

2. Edit the Nginx upgrade script. In the original setup, LNMP 1.3 was being used, though the path can be changed for other versions.

cd /lnmp1.3-full/include
vi upgrade_nginx.sh

Find the line beginning with ./configure --user=www --group=www --prefix=/usr/local/nginx and append the PageSpeed module path at the end, replacing the module directory name with the one you actually downloaded.

--add-module=/opt/incubator-pagespeed-ngx-1.13.35.2-stable

Then rebuild Nginx:

./upgrade_nginx.sh

If there are no other errors, Nginx will be upgraded or rebuilt and ngx_pagespeed will be installed at the same time.

Install ngx_pagespeed on BaoTa Panel

BaoTa provides a graphical interface, but underneath it still uses shell scripts. That means it is also possible to add ngx_pagespeed to Nginx there. The relevant installation script is usually located at /www/server/panel/install/nginx.sh. Modify that file, add the compile option, then reinstall Nginx from the panel using a compile-based installation.

After installation, you can place the PageSpeed directives into the site configuration or pseudo-static rules as needed.

A common CentOS 6 error and how to fix it

Some users see an error like this while installing ngx_pagespeed:

build_from_source=false error: module ngx_pagespeed requires the pagespeed optimization library

That error usually means the PSOL optimization library cannot be used correctly. On CentOS 6, the real issue is often that GCC is too old. Installing a newer toolchain solves it.

cd /etc/yum.repos.d && wget http://people.centos.org/tru/devtools-2/devtools-2.repo 
yum -y install devtoolset-2-gcc devtoolset-2-binutils devtoolset-2-gcc-c++

Those packages install into /opt/rh/devtoolset-2. To compile Nginx with that compiler, edit upgrade_nginx.sh again and add the compiler path to the configure command.

./configure (中间省略) --add-module=pagespeed代码路径 --with-cc=/opt/rh/devtoolset-2/root/usr/bin/gcc

The final command then looks something like this:

./configure --user=www --group=www --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_v2_module --with-http_gzip_static_module --with-ipv6 --with-http_sub_module ${Nginx_With_Openssl} ${NginxMAOpt} ${Nginx_Modules_Options} --add-module=/opt/incubator-pagespeed-ngx-1.13.35.2-stable --with-cc=/opt/rh/devtoolset-2/root/usr/bin/gcc

If the server is CentOS 7 and you still see the “build_from_source=false checking for psol … not found” message, another possible cause is a missing libuuid-devel package.

yum install -y libuuid-devel

Configure Nginx PageSpeed to accelerate WordPress

After installation, ngx_pagespeed is enabled automatically, but it still needs to be configured properly. The following sample configuration shows a practical starting point for accelerating a WordPress site. You can enable or disable individual filters as needed.

# on enables, off disables
pagespeed on;

# Respect the HTTP Vary header
pagespeed RespectVary on;

# Lowercase HTML tags
pagespeed LowercaseHtmlNames on;

# Compress resources even when Cache-Control: no-transform is present
#pagespeed DisableRewriteOnNoTransform off;

# Preserve relative URLs
pagespeed PreserveUrlRelativity on;
pagespeed XHeaderValue "Powered By ngx_pagespeed";

# Enable HTTPS fetching
pagespeed FetchHttps enable;

# Configure the file cache
pagespeed FileCachePath "/var/ngx_pagespeed/";
pagespeed FileCacheSizeKb 2048000;
pagespeed FileCacheCleanIntervalMs 43200000;
pagespeed FileCacheInodeLimit 500000;

# Rewrite level
# pagespeed RewriteLevel PassThrough;
pagespeed RewriteLevel OptimizeForBandwidth;

# Directories or files that should not be rewritten
pagespeed Disallow "*/wp-admin/*";
pagespeed Disallow "*/wp-login.php*";

# Remove unnecessary URL prefixes
#pagespeed EnableFilters trim_urls;

# Collapse HTML whitespace
pagespeed EnableFilters collapse_whitespace;

# Remove HTML comments
pagespeed EnableFilters remove_comments;

# Insert DNS prefetch
pagespeed EnableFilters insert_dns_prefetch;

# Defer JavaScript
pagespeed EnableFilters defer_javascript;

# Combine CSS
pagespeed EnableFilters combine_css;

# Rewrite CSS
pagespeed EnableFilters rewrite_css;

# Prioritize critical CSS
pagespeed EnableFilters prioritize_critical_css;

# Inline Google font CSS
pagespeed EnableFilters inline_google_font_css;

# Rewrite JS
pagespeed EnableFilters rewrite_javascript;

# Combine JS
pagespeed EnableFilters combine_javascript;

There are many more directives available in the official ngx_pagespeed documentation, but even a configuration like the one above can make a visible difference for WordPress front-end performance.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *