本文编写于 1446 天前,最后修改于 1306 天前,其中某些信息可能已经过时。
Ngx_pagespeed官網: http://ngxpagespeed.com/
項目Github主頁: https://github.com/pagespeed/ngx_pagespeed (詳細配置方法,也可以看這裡)
GoogleDevelopers:https://developers.google.com/speed/docs/mod_pagespeed
主要功能
圖像優化:剝離元數據、動態調整,重新壓縮 CSS和JavaScript壓縮、合併、級聯、內聯 小資源內聯 推遲圖像和JavaScript加載 對HTML重寫、壓縮空格、去除注釋等 提升緩存周期 *等。實測對靜態頁壓縮效果一般,生產環境穩定第一,改使用第三方CDN壓縮。
0x01 一鍵腳本
要求:GCC版本 > 4.8
查看本機GCC版本:
gcc -dumpversion
查看CENTOS版本:
cat /etc/redhat-release
建立缓存目录:
mkdir -m 777 /tmp/ngx_pagespeed_cache/
安裝:
wget https://www.gaomeng.net.cn/source/script/ngx_pagespeed_auto-madlifer/nps-auto.sh && bash nps-auto.sh
#!/bin/bash
Green_font="[32m" && Yellow_font="[33m" && Red_font="[31m" && Font_suffix="[0m"
Info="${Green_font}[Info]${Font_suffix}"
Error="${Red_font}[Error]${Font_suffix}"
NGX_DIR=/www/server/nginx
NPS_VESION=1.13.35.2-stable
echo -e "${Green_font}
${Font_suffix}"
download_ngx_pagespeed(){
cd ${NGX_DIR}/src
wget https://github.com/apache/incubator-pagespeed-ngx/archive/v${NPS_VESION}.zip
unzip v${NPS_VESION}.zip
rm v${NPS_VESION}.zip
NPS_DIR=$(find . -name "*pagespeed-ngx-${NPS_VESION}" -type d)
mv $NPS_DIR ngx_pagespeed
cd ngx_pagespeed
NPS_RELEASE_NUMBER=${NPS_VESION/beta/}
NPS_RELEASE_NUMBER=${NPS_VESION/stable/}
PSPL_URL=https://dl.google.com/dl/page-speed/psol/${NPS_RELEASE_NUMBER}.tar.gz
[ -e scripts/format_binary_url.sh ]
PSPL_URL=$(scripts/format_binary_url.sh PSOL_BINARY_URL)
wget ${PSPL_URL}
tar -xzvf $(basename ${PSPL_URL})
rm $(basename ${PSPL_URL})
}
install_ngx_pagespeed(){
cd ${NGX_DIR}/src
NGX_CONF=`/usr/bin/nginx -V 2>&1 >/dev/null | grep 'configure' --color | awk -F':' '{print $2;}'`
NGX_CONF="--add-module=${NGX_DIR}/src/ngx_pagespeed $NGX_CONF"
./configure $NGX_CONF
make
make install
}
check_system() {
if grep -Eqii "CentOS" /etc/issue || grep -Eq "CentOS" /etc/*-release; then
DISTRO='CentOS'
PM='yum'
elif grep -Eqi "Red Hat Enterprise Linux Server" /etc/issue || grep -Eq "Red Hat Enterprise Linux Server" /etc/*-release; then
DISTRO='RHEL'
PM='yum'
elif grep -Eqi "Aliyun" /etc/issue || grep -Eq "Aliyun" /etc/*-release; then
DISTRO='Aliyun'
PM='yum'
elif grep -Eqi "Debian" /etc/issue || grep -Eq "Debian" /etc/*-release; then
DISTRO='Debian'
PM='apt'
elif grep -Eqi "Ubuntu" /etc/issue || grep -Eq "Ubuntu" /etc/*-release; then
DISTRO='Ubuntu'
PM='sudo'
else
DISTRO='unknow'
fi
}
install_basic(){
case ${PM} in
yum)
yum -y install sudo
yum -y update
sudo yum -y install gcc-c++ pcre-devel zlib-devel make unzip libuuid-devel
;;
apt)
apt -y install sudo
sudo apt -y update
sudo apt-get -y install build-essential zlib1g-dev libpcre3 libpcre3-dev unzip uuid-dev
;;
sudo)
sudo apt -y update
sudo apt-get -y install build-essential zlib1g-dev libpcre3 libpcre3-dev unzip uuid-dev
;;
*)
echo -e "${Error} 不支持您的系统 !"
;;
esac
echo -e "${Info} 模块依赖安装完成 !"
}
check_root(){
"`id -u`" != "0" && echo -e "${Error} 请先进入root账户 !"
}
check_gcc(){
gcc --version && echo -e "${Info} 请先确认gcc版本>=4.8! 输入任意按键来确认?"
read aNum
}
restart_ngx(){
service nginx restart
echo -e "${Info} 已重启Nginx!"
}
temp_swap_add(){
sudo dd if=/dev/zero of=/swapfile bs=64M count=16
sudo mkswap /swapfile
sudo swapon /swapfile
echo -e "${Info} 临时增加Swap以解决编译中内存不足崩溃!"
}
temp_swap_del(){
sudo swapoff /swapfile
sudo rm /swapfile
echo -e "${Info} 删除临时增加的swap空间!"
}
setup(){
check_root
check_system
check_gcc
install_basic
temp_swap_add
echo -e "${Info} 安装前配置已完成!!"
}
install(){
download_ngx_pagespeed
install_ngx_pagespeed
temp_swap_del
restart_ngx
echo -e "${Info} ngx_pagespeed 模块安装完成!"
}
status(){
NGX_CONF=`/usr/bin/nginx -V 2>&1 >/dev/null`
echo $NGX_CONF | grep -q pagespeed
if [ $? = 0 ]; then
echo -e "${Info} Pagespeed正在运行 !"
else
echo -e "${Error} Pagespeed没有运行 !"
fi
}
echo -e "${Info} 选择你要使用的功能: "
echo -e "1.安装前配置
2.进行安装
3.检查运行状态
"
read -p "输入数字以选择:" function
while ! "${function}" =~ ^[1-4]$
do
echo -e "${Error} 无效输入"
echo -e "${Info} 请重新选择" && read -p "输入数字以选择:" function
done
if "${function}" == "1" ; then
setup
elif "${function}" == "2" ; then
install
elif "${function}" == "3" ; then
status
fi
0x02 Nginx配置文件修改
http
{
include mime.types;
#include luawaf.conf;
include proxy.conf;
在上面代碼下增加:
#启用ngx_pagespeed 开始
pagespeed on;
#列出优化过程中所有失败的请求,debug 时很有用,失败的信息会打印到 error log 里
#pagespeed ListOutstandingUrlsOnError on;
#配置服务器缓存位置和自动清除触发条件(空间大小、时限)
#路径请提前创建好,可以放在内存也可以放在临时文件夹中
pagespeed CreateSharedMemoryMetadataCache /tmp/ngx_pagespeed_cache 51200;
pagespeed DefaultSharedMemoryCacheKB 51200;
pagespeed FileCachePath /tmp/ngx_pagespeed_cache;
pagespeed FileCacheSizeKb 2048000;
pagespeed FileCacheCleanIntervalMs 43200000;
pagespeed FileCacheInodeLimit 500000;
#过滤器级别(自定义模式)
pagespeed RewriteLevel PassThrough;
#一个标识而已(若在浏览器开发者工具里的链接请求响应标头看到此标识,则说明 PageSpeed 生效)
pagespeed XHeaderValue "Powered By daniao.org";
#HTML页面链接转小写(SEO 优化,推荐)
pagespeed LowercaseHtmlNames on;
#重置 HTTP Vary 头 除非有特殊需求,建议不开启,默认配置往往是最佳配置
#pagespeed RespectVary on;
#PageSpeed能够根据响应头中指定的任何内容安全策略调整其优化
pagespeed HonorCsp on;
#PageSpeed 默认遵守 Cache-Control: no-transform 协议, 表示不可被中间代理软件改写,如果想让优化效果最大化,可以关闭
#pagespeed DisableRewriteOnNoTransform off;
# 启用 样式属性/CSS/JavaScript/Images 重写,其它功能的先决开关
pagespeed EnableFilters rewrite_style_attributes,rewrite_css,rewrite_javascript,rewrite_images;
#重写CSS文件,以便首先加载渲染页面的CSS规则。
pagespeed EnableFilters prioritize_critical_css;
###########缓存 ##########
#相当于同时使用了extend_cache_images, extend_cache_scripts和 extend_cache_css
pagespeed EnableFilters extend_cache;
pagespeed EnableFilters extend_cache_pdfs;
pagespeed EnableFilters local_storage_cache;
#开启使用Redis(和memcached只能先其一)
#pagespeed RedisServer "127.0.0.1:6379";
#memcached优化,如果没有memcached优化请删去
pagespeed MemcachedThreads 1;
pagespeed MemcachedServers "127.0.0.1:11211";
######## 过滤规则 ########
#过滤不需要启用的目录或文件
#pagespeed Disallow "*/wp-admin/*";
#pagespeed Disallow "*/wp-login.php*";
pagespeed Disallow "*/vps-pingfen/";
#启用压缩空白过滤器
pagespeed EnableFilters collapse_whitespace;
#预解析DNS查询
pagespeed EnableFilters insert_dns_prefetch;
########JS和CSS########
#启用JavaScript库卸载 #谷歌被QQ,并不确定这个设置有没有副作用
#pagespeed EnableFilters canonicalize_javascript_libraries;
#把多个CSS文件合并成一个CSS文件(比较容易引起主题版面混乱,所以我禁用了
#pagespeed EnableFilters combine_css;
#重写CSS,首先加载渲染页面的CSS规则
pagespeed EnableFilters prioritize_critical_css;
#把多个JavaScript文件合并成一个JavaScript文件,禁用原因同上,大家可以酌情开启
#pagespeed EnableFilters combine_javascript;
#删除带默认属性的标签
pagespeed EnableFilters elide_attributes;
#更换被导入文件的@import,精简CSS文件
pagespeed EnableFilters flatten_css_imports;
pagespeed CssFlattenMaxBytes 5120;
#启用JavaScript缩小机制
pagespeed EnableFilters rewrite_javascript;
####### 图片########
#延时加载图片
pagespeed EnableFilters lazyload_images;
#不加载显示区域以外的图片
pagespeed LazyloadImagesAfterOnload off;
pagespeed LazyloadImagesBlankUrl "https://cdn.daniao.org/1.gif";
#启用图片优化机制(主要是 inline_images, recompress_images, convert_to_webp_lossless(这个命令会把PNG和静态Gif图片转化为webp), and resize_images.)
pagespeed EnableFilters rewrite_images;
#组合 convert_gif_to_png, convert_jpeg_to_progressive, convert_jpeg_to_webp, convert_png_to_jpeg, jpeg_subsampling, recompress_jpeg, recompress_png, recompress_webp, #strip_image_color_profile, and strip_image_meta_data.
pagespeed EnableFilters recompress_images;
#将JPEG图片转化为webp格式
pagespeed EnableFilters convert_jpeg_to_webp;
#将动画Gif图片转化为动画webp格式
pagespeed EnableFilters convert_to_webp_animated;
pagespeed EnableFilters inline_preview_images;
pagespeed EnableFilters resize_mobile_images;
pagespeed EnableFilters responsive_images,resize_images;
pagespeed EnableFilters insert_image_dimensions;
pagespeed EnableFilters resize_rendered_image_dimensions;
pagespeed EnableFilters strip_image_meta_data;
pagespeed EnableFilters convert_jpeg_to_webp,convert_to_webp_lossless,convert_to_webp_animated;
pagespeed EnableFilters sprite_images;
pagespeed EnableFilters convert_png_to_jpeg,convert_jpeg_to_webp;
#让JS里引用的图片也加入优化
pagespeed InPlaceResourceOptimization on;
pagespeed EnableFilters in_place_optimize_for_browser;
#启用ngx_pagespeed 结束
0x03 站點設置:打開網站設置加入以下代碼
#启用ngx_pagespeed 开始
pagespeed EnableFilters rewrite_domains;
#pagespeed Domain https://www.yourdomain.com;
#pagespeed MapRewriteDomain https://cdn.yourdomain.org https://www.yourdomain.org;
#不能删 。确保对pagespeed优化资源的请求进入pagespeed处理程序并且没有额外的头部信息
location ~ "\.pagespeed\.([a-z]\.)?[a-z]{2}\.[^.]{10}\.[^.]+" { add_header "" ""; }
location ~ "^/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_console { allow 127.0.0.1; deny all; }
location ~ ^/pagespeed_admin { allow 127.0.0.1; deny all; }
location ~ ^/pagespeed_global_admin { allow 127.0.0.1; deny all; }
#启用ngx_pagespeed 结束
0x04 清理緩存
rm -rf /tmp/ngx_pagespeed_cache/*