# PageSpeed Modules

Nginx 配置 PageSpeed Modules

文章使用 apt 安装(升级) Nginx (免设置编译参数),再获取源码添加 PageSpeed Modules 参数进行编译,然后替换二进制文件

注意

网站出现错误时请尝试减去部分配置,使用该模块可能会减缓网站的访问速度

提示

随着版软件版本的更新,文章请以最新版本为准

Last updated on 2020-02-18


建议

Nginx 源码版本和 apt 安装的 Nginx 版本一致

# 安装依赖

sudo apt install build-essential zlib1g-dev libpcre3 libpcre3-dev unzip uuid-dev
sudo apt install openssl libssl-dev
  • Ubuntu 18.04
sudo apt install libgd-dev libgeoip-dev libssl-dev libpcre++-dev libxslt1-dev

# 安装 Nginx

# 编译

  • 获取 PageSpeed Modules
wget https://github.com/apache/incubator-pagespeed-ngx/archive/latest-stable.tar.gz
tar -xzvf latest-stable.tar.gz
  • 获取 Nginx 源码
wget http://nginx.org/download/nginx-1.14.0.tar.gz
tar -xzvf nginx-1.14.0.tar.gz
rm nginx-1.14.0.tar.gz
  • 查看当前 Nginx 编译的参数
nginx -V

假设返回信息如下

nginx version: nginx/1.14.0
built by gcc 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.10)
built with OpenSSL 1.0.2g 1 Mar 2016
TLS SNI support enabled
configure arguments: --with-cc-opt='-g -O2 -fdebug-prefix-map=/build/nginx-FIJPpj/nginx-1.14.0=. -fstack-protector-strong -Wformat -Werror=format-security -fPIC -Wdate-time -D_FORTIFY_SOURCE=2' --with-ld-opt='-Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now -fPIC' --prefix=/usr/share/nginx --conf-path=/etc/nginx/nginx.conf --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --lock-path=/var/lock/nginx.lock --pid-path=/run/nginx.pid --modules-path=/usr/lib/nginx/modules --http-client-body-temp-path=/var/lib/nginx/body --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --http-proxy-temp-path=/var/lib/nginx/proxy --http-scgi-temp-path=/var/lib/nginx/scgi --http-uwsgi-temp-path=/var/lib/nginx/uwsgi --with-debug --with-pcre-jit --with-http_ssl_module --with-http_stub_status_module --with-http_realip_module --with-http_auth_request_module --with-http_v2_module --with-http_dav_module --with-http_slice_module --with-threads --with-http_addition_module --with-http_geoip_module=dynamic --with-http_gunzip_module --with-http_gzip_static_module --with-http_image_filter_module=dynamic --with-http_sub_module --with-http_xslt_module=dynamic --with-stream=dynamic --with-stream_ssl_module --with-mail=dynamic --with-mail_ssl_module
  • 将 PageSpeed 参数添加到 configure 中的最后面
--add-module=../incubator-pagespeed-ngx-latest-stable

完整示例如下(参数在最后面)

提示

参数中可能包含了 Debug 模块,如果不需要可以找到 --with-debug 并将其删除即可

sudo ./configure --with-cc-opt='-g -O2 -fdebug-prefix-map=/build/nginx-FIJPpj/nginx-1.14.0=. -fstack-protector-strong -Wformat -Werror=format-security -fPIC -Wdate-time -D_FORTIFY_SOURCE=2' --with-ld-opt='-Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now -fPIC' --prefix=/usr/share/nginx --conf-path=/etc/nginx/nginx.conf --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --lock-path=/var/lock/nginx.lock --pid-path=/run/nginx.pid --modules-path=/usr/lib/nginx/modules --http-client-body-temp-path=/var/lib/nginx/body --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --http-proxy-temp-path=/var/lib/nginx/proxy --http-scgi-temp-path=/var/lib/nginx/scgi --http-uwsgi-temp-path=/var/lib/nginx/uwsgi --with-debug --with-pcre-jit --with-http_ssl_module --with-http_stub_status_module --with-http_realip_module --with-http_auth_request_module --with-http_v2_module --with-http_dav_module --with-http_slice_module --with-threads --with-http_addition_module --with-http_geoip_module=dynamic --with-http_gunzip_module --with-http_gzip_static_module --with-http_image_filter_module=dynamic --with-http_sub_module --with-http_xslt_module=dynamic --with-stream=dynamic --with-stream_ssl_module --with-mail=dynamic --with-mail_ssl_module --add-module=../incubator-pagespeed-ngx-latest-stable
  • 执行上述命令之后会出现如下提示

提示

如果上一步没有移除 --with-debug 模块,则会弹出以下提示

You have set --with-debug for building nginx, but precompiled Debug binaries for
PSOL, which ngx_pagespeed depends on, aren't available.  If you're trying to
debug PSOL you need to build it from source.  If you just want to run nginx with
debug-level logging you can use the Release binaries.

Use the available Release binaries? [Y/n]

直接回车即可,然后继续下面的步骤

ngx_pagespeed: pagespeed optimization library not found:
./configure: 31: ../incubator-pagespeed-ngx-latest-stable/config: [[: not found

You need to separately download the pagespeed library:
$ cd ../incubator-pagespeed-ngx-latest-stable
$ wget https://dl.google.com/dl/page-speed/psol/1.12.34.2-x64.tar.gz
$ tar -xzvf 1.12.34.2-x64.tar.gz # expands to psol/

Or see the installation instructions:
https://developers.google.com/speed/pagespeed/module/build_ngx_pagespeed_from_source
  • 按提示操作
cd ../incubator-pagespeed-ngx-latest-stable
wget https://dl.google.com/dl/page-speed/psol/1.12.34.2-x64.tar.gz
tar -xzvf 1.12.34.2-x64.tar.gz
cd ../nginx-1.14.0
  • 再次执行之前的 configure

  • 编译

sudo make
sudo make install

替换二进制文件

sudo cp objs/nginx /usr/sbin
  • 验证
nginx -V

# 配置 PageSpeed Modules

  • 新建缓存目录
sudo mkdir /var/cache/pagespeed/
  • 创建配置文件
cd /etc/nginx/conf.d && sudo vi pagespeed.conf

内容示例如下:

# on 启 off 关闭
pagespeed on;
# 级别 CoreFilters
pagespeed RewriteLevel CoreFilters;
# 缓存配置
pagespeed FileCachePath "/var/cache/pagespeed/";
pagespeed FileCacheSizeKb 2048000;
pagespeed FileCacheCleanIntervalMs 3600000;
pagespeed FileCacheInodeLimit 500000;
# 将 head 文档中的多个元素合并为一个元素
pagespeed EnableFilters combine_heads;
# 将大的js外部化为可缓存文件
pagespeed EnableFilters outline_javascript;
# js最低缓存大小 单位 B
pagespeed JsOutlineMinBytes 3000;
# 将CSS元素移动到<script>标记上方
pagespeed EnableFilters move_css_above_scripts;
# 将CSS移至Head
pagespeed EnableFilters move_css_to_head;
# 重写CSS样式属性
pagespeed EnableFilters rewrite_style_attributes_with_url,rewrite_css,rewrite_images;
# 优先加载必要的CSS资源
pagespeed EnableFilters prioritize_critical_css;
# 将谷歌字体使用的小CSS文件内联到HTML文档中
pagespeed EnableFilters inline_google_font_css;
# 删除HTML文件中的注释(但不包括内联JavaScript或CSS)
pagespeed EnableFilters remove_comments;
# 删除HTML文件中多余的空格
pagespeed EnableFilters collapse_whitespace;
# 根据HTML规范删除不重要的属性
pagespeed EnableFilters elide_attributes;
# 缩短URL
pagespeed EnableFilters trim_urls;
# 删除不必要的HTML属性的符号
pagespeed EnableFilters remove_quotes;
# 推迟加载js
pagespeed EnableFilters defer_javascript;
# 删除重复的图像
pagespeed EnableFilters dedup_inlined_images;
# 推迟加载图像
pagespeed EnableFilters lazyload_images;
# 预解析DNS
pagespeed EnableFilters insert_dns_prefetch;
# 对特定的浏览器进行优化
pagespeed EnableFilters in_place_optimize_for_browser;
# 不优化IE浏览器
pagespeed PrivateNotVaryForIE off;
# URL 缓存
pagespeed LRUCacheKbPerProcess     8192;
pagespeed LRUCacheByteLimit        16384;
# 为PageSpeed配置HTTPCache压缩
pagespeed HttpCacheCompressionLevel 9;
# 使用扩展缓存
pagespeed EnableFilters extend_cache;

# 应用

提示

由于 Nginx 已经默认加载 conf.d 中所有的 .conf 文件,所以无需单独在虚拟机中引用 pagespeed.conf

  • 单独在虚拟主机中应用

单独应用需要将 pagespeed.conf 移动到 conf.d 之外的目录(例如 /etc/nginx)且需要将缓存配置添加到 nginx.conf

pagespeed FileCachePath "/var/cache/pagespeed/";
pagespeed FileCacheSizeKb 2048000;
pagespeed FileCacheCleanIntervalMs 3600000;
pagespeed FileCacheInodeLimit 500000;

虚拟机配置中引用

...
server {
  ...
  include /etc/nginx/pagespeed.conf;
  ...
...

优化配置文件

  • 添加下面内容到虚拟主机配置中
# 禁用优化
pagespeed Disallow "*/admin/*";

# 为pagespeed启用HTTPS (可选)
# pagespeed FetchHttps enable;
# pagespeed LoadFromFile "https://example.com" "/var/www/wordpress/";
location ~ "\.pagespeed\.([a-z]\.)?[a-z]{2}\.[^.]{10}\.[^.]+" {
add_header "" "";
}

location ~ "^/ngx_pagespeed_static/" { }
location ~ "^/ngx_pagespeed_beacon$" { }

# 可选配置

虚拟机中配置内存缓存

  • 编辑虚拟主机配置文件并把下面内容添加到顶部
pagespeed CreateSharedMemoryMetadataCache "/var/cache/pagespeed/" 204800;

注意

必须在顶部

使用 Gzip 压缩的资源

  • 必须在引用 pagespeed.conf 之后添加 Gizp 配置
  • 编辑 nginx.conf 并启用 Gzip ,示例如下
pagespeed FetchWithGzip on;
gzip on;
gzip_min_length 1k;
gzip_buffers 32 4k;
gzip_http_version 1.0;
gzip_comp_level 9;
gzip_vary on;
gzip_proxied any;
gzip_disable "MSIE [1-6]\.";
gzip_types text/css text/xml image/gif image/jpeg application/javascript application/atom+xml application/rss+xml image/png image/tiff image/x-icon image/x-jng image/x-ms-bmp image/svg+xml application/font-woff application/java-archive application/json;

为 PageSpeed 配置 Redis 缓存

  • 安装 Redis Server
sudo apt install redis-server

Nginx 配置

# Redis主机地址,默认端口是 6379
pagespeed RedisServer "127.0.0.1:6379";
# PageSpeed在超时请求之前等待Redis响应的时间,默认为50ms
pagespeed RedisTimeoutUs 50;
# PageSpeed在再次尝试连接之前从Redis发出错误后等待的时间,默认为1秒
pagespeed RedisReconnectionDelayMs 1;

注意

不支持连接带密码的 Redis 服务器

# 解决 Nginx Status 中的错误

  • 错误 一

查看 Nginx 运行状态

/etc/init.d/nginx status

显示如下

Oct 08 11:27:37 VM-2-17-ubuntu systemd[1]: nginx.service: PID file /var/run/nginx.pid not

使用 systemctl 启用 nginx

systemctl enable nginx.service

执行之后输出如下

Synchronizing state of nginx.service with SysV init with /lib/systemd/systemd-sysv-install...
Executing /lib/systemd/systemd-sysv-install enable nginx

使用 init.d 停止 Nginx

/etc/init.d/nginx stop

启动 Nginx

systemctl start nginx
Oct 08 15:10:07 VM-2-17-ubuntu systemd[1]: Starting nginx - high performance web server...
Oct 08 15:10:07 VM-2-17-ubuntu systemd[1]: Started nginx - high performance web server.

之后使用 systemctl 操作 nginx 即可

或者尝试以下命令

systemctl daemon-reload && systemctl restart nginx
  • 错误 二

Failed to read PID from file /run/nginx.pid: Invalid argument

# 其他

Google 网站测速

文章部分内容参考链接: