Optimize Front-End Pages with ngx_pagespeed for Faster WordPress Loading

Nginx PageSpeed ​​is an extension module of Nginx. Its main function is to optimize the front-end page of the website on the server side so that the front-end page conforms to thePageSpeed ​​InsightsWith the guiding principle of PageSpeed, website developers can be a little more relaxed when developing front-end pages and hand over all front-end optimization tasks to the server. Although this will increase the server load; from the perspective of reducing the number of client requests, it is worth sacrificing some server performance. Anyway, servers are getting cheaper now. At most, just increase the server configuration. Let’s take a look at how to install and use Nginx PageSpeed.

The main functions of the ngx_pagespeed module are as follows

ngx_pagespeed provides us with almost all the functions needed to optimize the front-end page of the website. Here are some of the more commonly used and important functions. Other functions can be found atngx_pagespeed official documentationCheck.

  • Image optimization: remove image metadata, dynamically adjust, recompress
  • CSS and JavaScript are compressed, merged, cascaded, and inlined, and the CSS required by the current page is directly placed on the page, complying withPageSpeedInsights’ “Clear rendering-blocking JavaScript and CSS” principles from above-the-fold content.
  • Small resources are inlined, such as relatively small images, directly converted into base64 format and placed in HTML.
  • Defer image and JavaScript loading, only load images currently displayed on the screen, and load JavaScript asynchronously
  • Rewrite HTML, compress spaces, remove comments, etc. to remove unnecessary content from HTML pages and reduce the size of HTML.
  • Improve the cache cycle and increase the cache expiration time of static resources.

The following is the score tested by PageSpeed ​​Insights after this site was optimized using ngx_pagespeed. Whether it is mobile or desktop, both reached 100 points. This is a height that is difficult to achieve by manually optimizing front-end pages. Of course, the optimization process is dynamic, and not every page can reach this score at any time, but overall, after using ngx_pagespeed optimization, the opening speed of the front-end page is indeed much faster, which can be distinguished with the naked eye.

Solve the dependencies required to install ngx_pagespeed

Before installation, you must first solve the dependency environment required to install or upgrade ngx_pagespeed.

RedHat, CentOS, or Fedora

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

Ubuntu or Debian

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

If it is already installed, you need to update the dependencies (requires gcc ≥ 4.8 or clang ≥ 3.3)

How to install ngx_pagespeed via LNMP

Since I am using Jun Ge’s LNMP one-click installation script, I directly edit the script to upgrade Nginx, add the parameters to compile ngx_pagespeed, and upgrade Nginx. Of course, if you don’t want to upgrade, just enter the current Nginx version number directly, which is equivalent to reinstalling it.

1. First, download Page Speed ​​according to the official tutorial and save the following command asdownload_pagespeed.shfile and then runchmod +x download_pagespeed.shGive the file executable permissions and then run./download_pagespeed.shThe source code of the ngx_pagespeed module will be automatically downloaded and decompressed.

#[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, when following the official tutorial, you may encounter a situation where you cannot download PSOL. In this case, just follow the address below to download the corresponding version of PSOL.

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

2. Then edit the Nginx upgrade script

I am using LNMP 1.3. For other versions, just change the installation path.

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

turn up./configure --user=www --group=www --prefix=/usr/local/nginx, add at the end of this line of code, wherengx_pagespeed-1.13.35.2-stableIt is the directory name of the PageSpeed ​​module downloaded in the first step. Just replace it according to the actual situation.

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

Then update Nginx. You can choose to upgrade the Nginx version as needed. Generally, choose the latest stable version.

./upgrade_nginx.sh

After more than ten minutes, if no other errors are prompted, ngx_pagespeed will be installed while Nginx is upgraded to the specified version.

Install the ngx_pagespeed module on the Pagoda panel

Although the Pagoda panel is a graphical interface, it ultimately performs command line operations, so we can also add the ngx_pagespeed module to Nginx. The script file path for the Pagoda panel to install Nginx is:/www/server/panel/install/nginx.sh, we modify this file, add compilation configuration, and then reinstall Nginx in the background. Just select compile and install during installation.

After the installation is complete, just add the Pagespeed configuration directly in the website configuration or pseudo-static in the site settings.

Common errors and solutions when installing ngx_pagespeed on Centos 6

Some friends encountered the following error when installing ngx_pagespeed:

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

This means that the pagespeed optimization library is required, which is the psol file downloaded above. It has been downloaded obviously, but why can’t I find it? This is because the gcc version of Centos 6 is lower and cannot meet the requirements for installing ngx_pagespeed. At this time, just upgrade gcc.

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++

The above command places the installed files in /opt/rh/devtoolset-2. You need to use this gcc to edit. When you need to edit again, specify the location of gcc, re-edit upgrade_nginx.sh, and add the following command at the end of the file.

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

Finally, the upgrade_nginx.sh command to edit Nginx should look 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 system is CentOS7 and it still prompts “build_from_source=false checking for psol… not found”, it may be that libuuid-devel is not installed. Just run the following command to install it.

yum install -y libuuid-devel

Configuring Nginx PageSpeed ​​to accelerate our WordPress

After installation, ngx_pagespeed has been automatically enabled. After pagespeed is enabled through the Nginx configuration file, PageSpeed ​​can serve our website. Below is the ngx_pagespeed configuration file I use for your reference. You can enable or disable certain modules according to your own needs. More ngx_pagespeed configuration can be found in Qingdaongx_pagespeed official documentationCheck.

# on 启用,off 关闭
pagespeed on;

# 重置 http Vary 头
pagespeed RespectVary on;

# html字符转小写
pagespeed LowercaseHtmlNames on;

# 压缩带 Cache-Control: no-transform 标记的资源
#pagespeed DisableRewriteOnNoTransform off;

# 相对URL
pagespeed PreserveUrlRelativity on;
pagespeed XHeaderValue "Powered By ngx_pagespeed";

# 开启 https
pagespeed FetchHttps enable;

# 配置服务器缓存位置和自动清除触发条件(空间大小、时限)
pagespeed FileCachePath "/var/ngx_pagespeed/";
pagespeed FileCacheSizeKb 2048000;
pagespeed FileCacheCleanIntervalMs 43200000;
pagespeed FileCacheInodeLimit 500000;

# 过滤规则
# pagespeed RewriteLevel PassThrough;
pagespeed RewriteLevel OptimizeForBandwidth;

# 不需过滤的目录或文件
pagespeed Disallow "*/wp-admin/*";
pagespeed Disallow "*/wp-login.php*";

# 移除不必要的url前缀,开启可能会导致某些自动加载功能失效
#pagespeed EnableFilters trim_urls;

# 移除 html 空白
pagespeed EnableFilters collapse_whitespace;

# 移除 html 注释
pagespeed EnableFilters remove_comments;

# DNS 预加载
pagespeed EnableFilters insert_dns_prefetch;

# 延迟加载 JavaScript
pagespeed EnableFilters defer_javascript;

# 合并CSS
pagespeed EnableFilters combine_css;

# 压缩CSS
pagespeed EnableFilters rewrite_css;

# 重写CSS,优化加载渲染页面的CSS规则
pagespeed EnableFilters prioritize_critical_css;

# google字体直接写入html 目的是减少浏览器请求和DNS查询
pagespeed EnableFilters inline_google_font_css;

# 压缩 js
pagespeed EnableFilters rewrite_javascript;

# 合并 js
pagespeed EnableFilters combine_javascript;

# 重写样式属性
pagespeed EnableFilters rewrite_style_attributes;

# 压缩图片
pagespeed EnableFilters rewrite_images;

# 不加载显示区域以外的图片
pagespeed LazyloadImagesAfterOnload off;

# 图片预加载
pagespeed EnableFilters inline_preview_images;

# 调整图片大小
pagespeed EnableFilters resize_images;

# 移动端图片自适应重置
pagespeed EnableFilters resize_mobile_images;

# 图片延迟加载
pagespeed EnableFilters lazyload_images;

# 雪碧图片,图标很多的时候很有用
#pagespeed EnableFilters sprite_images;

# 扩展缓存 改善页面资源的可缓存性
pagespeed EnableFilters extend_cache;

# 不将规则应用在 wp-admin目录 和 wplogin.php页面
pagespeed Disallow "*/wp-admin/*";
pagespeed Disallow "*/wp-login.php*";
# 风险指数高,不建议开启
#pagespeed EnableFilters local_storage_cache;

# 不能删
location ~ ".pagespeed.([a-z].)?[a-z]{2}.[^.]{10}.[^.]+" {
add_header "" "";
}

location ~ "^/ngx_pagespeed_static/" { }

location ~ "^/ngx_pagespeed_beacon$" { }

location /ngx_pagespeed_statistics {
    allow 127.0.0.1;
    deny all;
}

location /ngx_pagespeed_global_statistics {
    allow 127.0.0.1;
    deny all;
}

location /ngx_pagespeed_message {
    allow 127.0.0.1;
    deny all;
}

location ~ ^/pagespeed_global_admin {
    allow 127.0.0.1;
    deny all;
}

pagespeed StatisticsPath /ngx_pagespeed_statistics;
pagespeed MessagesPath /ngx_pagespeed_message;
pagespeed ConsolePath /pagespeed_console;
pagespeed AdminPath /pagespeed_admin;

# 控制台 可通过 http://domain.com/ngx_pagespeed_admin 来查看控制台
pagespeed Statistics on;
pagespeed StatisticsLogging on;

pagespeed LogDir /var/log/pagespeed;

location /pagespeed_console {
    allow 127.0.0.1;
    deny all;
}

pagespeed AdminPath /ngx_pagespeed_admin;

location ~ ^/pagespeed_admin {
    allow 127.0.0.1;
    deny all;
}

# 日志限制
pagespeed StatisticsLoggingIntervalMs 60000;
pagespeed StatisticsLoggingMaxFileSizeKb 1024;

Related Posts

Leave a Reply

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