nginx下pagespeed使用詳解

1.簡介

PageSpeed 是一個款Google開源(Google出品必輸競品)用來自動優化網站的神器!,做爲Nginx組件,ngx_pagespeed將重寫你的網頁,讓用戶以更快的速度進行訪問。重寫的工做包括壓縮圖片、縮減CSS和JavaScript、擴展緩存時間css

2.安裝

官方安裝講解:地址html

2.1腳本安裝

能夠選擇使用自動腳本,能夠到的一個對應的nginx版本,而且編譯了pagespeed模塊java

查看該腳本的如何使用

$ bash <(curl -f -L -sS https://ngxpagespeed.com/install) --help

Usage: build_ngx_pagespeed.sh [options]

  Installs ngx_pagespeed and its dependencies.  Can optionally build and install
  nginx as well.  Can be run either as:

     bash <(curl -f -L -sS https://ngxpagespeed.com/install) [options]

  Or:

     git clone git@github.com:pagespeed/ngx_pagespeed.git
     cd ngx_pagespeed/
     git checkout <branch>
     scripts/build_ngx_pagespeed.sh [options]

Options:
  -v, --ngx-pagespeed-version <ngx_pagespeed version>
      What version of ngx_pagespeed to build.  Valid options include:
      * latest-beta
      * latest-stable
      * a version number, such as 1.11.33.4

      If you don't specify a version, defaults to latest-stable unless --devel
      is specified, in which case it defaults to master.

      This option doesn't make sense if we're running within an existing
      ngx_pagespeed checkout.

  -n, --nginx-version <nginx version>
      What version of nginx to build.  If not set, this script only prepares the
      ngx_pagespeed module, and expects you to handle including it when you
      build nginx.

      If you pass in 'latest' then this script scrapes the nginx download page
      and attempts to determine the latest version automatically.

  -m, --dynamic-module
      Build ngx_pagespeed as a dynamic module.

  -b, --builddir <directory>
      Where to build.  Defaults to $HOME.

  -p, --no-deps-check
      By default, this script checks for the packages it depends on and tries to
      install them.  If you have installed dependencies from source or are on a
      non-deb non-rpm system, this won't work.  In that case, install the
      dependencies yourself and pass --no-deps-check.

  -s, --psol-from-source
      Build PSOL from source instead of downloading a pre-built binary module.

  -l, --devel
      Sets up a development environment in ngx_pagespeed/nginx, building with
      testing-only dependencies.  Includes --psol-from-source, conflicts with
      --nginx-version.  Uses a 'git clone' checkout for ngx_pagespeed and nginx
      instead of downloading a tarball.

  -t, --build-type
      When building PSOL from source, what to tell it for BUILD_TYPE.  Defaults
      to 'Release' unless --devel is set in which case it defaults to 'Debug'.

  -y, --assume-yes
      Assume the answer to all prompts is 'yes, please continue'.  Intended for
      automated usage, such as buildbots.

  -a, --additional-nginx-configure-arguments
      When running ./configure for nginx, you may want to specify additional
      arguments, such as --with-http_ssl_module.  By default this script will
      pause and prompt you for them, but this option lets you pass them in.  For
      example, you might do:
        -a '--with-http_ssl_module --with-cc-opt="-I /usr/local/include"'

  -d, --dryrun
      Don't make any changes to the system, just print what changes you
      would have made.

  -h, --help
      Print this message and exit.

使用腳本自動安裝

咱們主要使用--nginx-version --additional-nginx-configure-arguments --dynamic-module這三個參數,選擇nginx的版本,編譯的參數,使用動態模塊node

bash <(curl -f -L -sS https://ngxpagespeed.com/install) \
     --nginx-version 1.12.1 \
     --dynamic-module \
     --additional-nginx-configure-arguments '--prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/lib/nginx/tmp/client_body --http-proxy-temp-path=/var/lib/nginx/tmp/proxy --http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi --http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi --http-scgi-temp-path=/var/lib/nginx/tmp/scgi --modules-path=/usr/lib64/nginx/modules --pid-path=/run/nginx.pid --lock-path=/run/lock/subsys/nginx --user=nginx --group=nginx --with-file-aio --with-ipv6 --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_addition_module --with-http_auth_request_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_degradation_module --with-http_stub_status_module --with-http_slice_module --with-mail=dynamic --with-mail_ssl_module --with-stream_ssl_module --with-threads --with-pcre --with-debug --with-cc-opt="-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -m64 -mtune=generic"'

腳本運行結果 相似下面nginx

test -f '/etc/nginx/nginx.conf' \
    || cp conf/nginx.conf '/etc/nginx/nginx.conf'
cp conf/nginx.conf '/etc/nginx/nginx.conf.default'
test -d '/run' \
    || mkdir -p '/run'
test -d '/var/log/nginx' \
    || mkdir -p '/var/log/nginx'
test -d '/usr/share/nginx/html' \
    || cp -R html '/usr/share/nginx'
test -d '/var/log/nginx' \
    || mkdir -p '/var/log/nginx'
test -d '/usr/lib64/nginx/modules' \
    || mkdir -p '/usr/lib64/nginx/modules'
test ! -f '/usr/lib64/nginx/modules/ngx_mail_module.so' \
    || mv '/usr/lib64/nginx/modules/ngx_mail_module.so' \
        '/usr/lib64/nginx/modules/ngx_mail_module.so.old'
cp objs/ngx_mail_module.so '/usr/lib64/nginx/modules/ngx_mail_module.so'
make[1]: Leaving directory `/root/nginx-1.12.1'

Nginx installed with ngx_pagespeed support compiled-in.

If this is a new installation you probably need an init script to
manage starting and stopping the nginx service.  See:
  http://wiki.nginx.org/InitScripts

You'll also need to configure ngx_pagespeed if you haven't yet:
  https://developers.google.com/speed/pagespeed/module/configuration

此時的變化是在相應的文件夾有個編譯好的nginx,還有個編譯好的ngx_pagespeed,進入相應文件夾,我使用的是root帳戶,這裏是/root下,多了兩個文件夾c++

incubator-pagespeed-ngx-latest-stable  nginx-1.12.1

/root/nginx-1.12.1/objs/nginx 其實就是編譯好的nginx可執行文件
/root/nginx-1.12.1/objs/ngx_pagespeed.so 是相應的模塊git

替換之前的nginx

(若是之前有yum安裝,而且還想使用之前的啓動腳本等,能夠考慮替換,能夠節省精力)github

下面就是替換我之前使用yum安裝的nginx,web

cp /usr/sbin/nginx /usr/sbin/nginx.bak #備份
cp /opt/nginx-1.12.1/objs/nginx /usr/sbin/nginx #替換程序
cp /opt/nginx-1.12.1/objs/ngx_pagespeed.so /usr/share/nginx/modules/ #替換模塊
systemctl restart nginx #重啓 nginx 服務

對於使用動態模塊,須要在主配置文件引入該模塊才能夠正常使用

load_module "modules/ngx_pagespeed.so";

這裏講一下使用yum安裝pagespeed的另外一種情形

可能你已經使用yum安裝了nginx,而且有不少依賴從新編譯可能會經過不了,而且發現已經自帶編譯了ngx_pagespeed,可是這個模塊其實並無真正下載,並不能直接使用,這種狀況下,只要按照該源的說明,安裝該模塊便可,進入相關源的頁面,https://webtatic.com/packages/nginx1/ 查看,而後安裝該模塊,這樣作也很方便

yum install nginx1w-module-pagespeed

2.2 手動安裝

先安裝基本依賴

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

構建pagespeed

cd /root
wget https://github.com/pagespeed/ngx_pagespeed/archive/release-1.6.29.5-beta.zip
unzip -q release-1.6.29.5-beta
cd ngx_pagespeed-release-1.6.29.5-beta
wget https://dl.google.com/dl/page-speed/psol/1.6.29.5.tar.gz
tar xzf 1.6.29.5.tar.gz -C ngx_pagespeed-release-1.6.29.5-beta

從新編譯安裝nginx

查看原Nginx配置

$ nginx -V
nginx version: nginx/1.12.1
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-16) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/lib/nginx/tmp/client_body --http-proxy-temp-path=/var/lib/nginx/tmp/proxy --http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi --http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi --http-scgi-temp-path=/var/lib/nginx/tmp/scgi --modules-path=/usr/lib64/nginx/modules --pid-path=/run/nginx.pid --lock-path=/run/lock/subsys/nginx --user=nginx --group=nginx --with-file-aio --with-ipv6 --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_addition_module --with-http_auth_request_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_degradation_module --with-http_stub_status_module --with-http_slice_module --with-mail=dynamic --with-mail_ssl_module --with-stream_ssl_module --with-threads --with-pcre --with-debug --with-cc-opt="-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -m64 -mtune=generic"

下載對應的源碼,知道yum 安裝nginx 的版本爲1.12.1,下載對應的源碼

wget http://nginx.org/download/nginx-1.12.1.tar.gz

原配置基礎上增長pagespeed模塊、

./configure --prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log
            ...
--add-module=/root/incubator-pagespeed-ngx-latest-stable

注意:若是你想要使用動態模塊安裝,則使用下面參數

--add-dynamic-module=/root/incubator-pagespeed-ngx-latest-stable

編譯

make && make install

一樣,若是有須要,可對執行文件進行備份替換,(根據本身實際狀況)

cp /usr/sbin/nginx /usr/sbin/nginx.bak #備份
cp /opt/nginx-1.12.1/objs/nginx /usr/sbin/nginx #替換
# 若是是動態模塊,同時須要 cp /opt/nginx-1.12.1/objs/ngx_pagespeed.so /usr/share/nginx/modules/ 
systemctl restart nginx #重啓 nginx 服務

3.配置

官方介紹:文檔地址

3.1 開啓,待機,關閉

開啓

開啓或關閉用 pagespeed on/off; 指令,例如:

load_module "modules/ngx_pagespeed.so";
http {
    ...
}
server {
    listen       80;
    pagespeed on;
    pagespeed FileCachePath /tmp/ngx_pagespeed_cache;
    ...
}

備機

pagespeed有一個備機模式,它不會改變你網站的原有配置,只有在如下兩種狀況下才會起做用

一、當你的請求帶着關於pagespeed的參數的時候,這時候會按照參數的配置返回給你響應。
二、當請求.pagespeed類的資源的時候。

pagespeed standby;

關閉

pagespeed unplugged;

注意:在1.12.34.1或更早版本之前,不要使用unlugged,會致使崩潰,請使用off

3.2 功能配置

Content-Security-Policy 頭部

從1.13.35.1開始,PageSpeed可以根據響應頭中指定的任何內容安全策略調整其優化。在這個版本中,您須要選擇加入這個特性,將來的版本可能會默認打開它。

pagespeed HonorCsp on;

HTTP Vary 協議

爲了達到優化的最大效果,對於資源文件(css、js,HTML 文件除外)等,PageSpeed 是不遵循 Vary HTTP 頭的,若是你但願 PageSpeed 徹底遵照 Vary 協議,可使用指令 pagespeed RespectVary on,不過除非有特殊需求,建議不開啓,默認配置每每是最佳配置。關於 Vary 大致的意思是就是 Vary 能夠標示同一個 url 能夠返回不一樣的內容,主要是給緩存中間件用的,避免只緩存單一內容。

Cache-Control: no-transform 協議

PageSpeed 默認遵照 Cache-Control: no-transform 協議, 表示不可被中間代理軟件改寫,若是想讓優化效果最大化,能夠這樣:

pagespeed DisableRewriteOnNoTransform off;
該指令,表示不遵照 Cache-Control: no-transform 協議。

LowercaseHtmlNames

HTML是不區分大小寫的,而XML和XHTML不是。Web性能最佳實踐建議使用小寫。通常來講,pagespeed會根據頭信息自動判斷是否是html頁面,可是有時候xml或者xhtml會使用錯誤的頭信息Content-Type: text/html,此時若是開啓了轉換成小寫,那麼當時xml和xhtml的時候可能會出現問題,因此pagespeed默認是不開啓的。

pagespeed LowercaseHtmlNames on;

ModifyCachingHeaders

PageSpeed 默認狀況下會修改 HTML 頁面彙總的 Meta 緩存標記,將其統一執爲 Cache-Control: no-cache, max-age=0,若是要保留 HTML 頁面原始的緩存控制指令,能夠這樣:

pagespeed ModifyCachingHeaders off;

不過官方並不建議關閉該指令,官方解釋以下:

Note: We do not suggest you turn this option off. It breaks PageSpeed's caching assumptions and can lead to unoptimized HTML being served from a proxy caches set up in front of the server. If you do turn it off, we suggest that you do not set long caching headers to HTML or users may receive stale or unoptimized content.

保留相對路徑

默認狀況下,PageSpeed 在優化時會把相對路徑轉成絕對路徑,若是所以而產生問題,你可使用以下指令來保留相對路徑

pagespeed PreserveUrlRelativity on;

NOTE: 官方文檔上說,將來會默認保留相對路徑,並且未來也會移除該指令。

開啓 debug 功能

ListOutstandingUrlsOnError 能夠列出優化過程當中全部失敗的請求,debug 時頗有用,失敗的信息會打印到 error log 裏。

pagespeed ListOutstandingUrlsOnError on;

https支持

若是你使用 https 協議,則須要加上以下指令以後,某些過濾器才能生效,從1.10版本開始,默認(fetchhttps是開啓的)

pagespeed FetchHttps enable;

能夠添加更多參數

pagespeed FetchHttps enable,allow_self_signed,allow_unknown_certificate_authority,allow_certificate_not_yet_valid;

開啓gzip

開啓gzip壓縮後,後會減小網絡資源傳輸的字節,參考示例:

pagespeed FetchWithGzip on;
gzip  on;
gzip_vary on;
# Turn on gzip for all content types that should benefit from it.
gzip_types application/ecmascript;
gzip_types application/javascript;
gzip_types application/json;
gzip_types application/pdf;
gzip_types application/postscript;
gzip_types application/x-javascript;
gzip_types image/svg+xml;
gzip_types text/css;
gzip_types text/csv;
# "gzip_types text/html" is assumed.
gzip_types text/javascript;
gzip_types text/plain;
gzip_types text/xml;

gzip_http_version 1.0;

3.3 管理頁面

PageSpeed 還提供了一個 web 的管理員界面來進行監控管理,很方便
配置以下:

http下配置

#PageSpeed管理頁面配置
#共享內存統計
pagespeed Statistics on;
#開啓虛擬主機統計信息
pagespeed UsePerVhostStatistics on;
pagespeed StatisticsLogging on;
pagespeed StatisticsLoggingIntervalMs 60000;
pagespeed StatisticsLoggingMaxFileSizeKb 1024;
#消息緩衝區大小,默認爲0,不保留消息
pagespeed MessageBufferSize 100000;
pagespeed LogDir /var/log/pagespeed;
pagespeed StatisticsPath /ngx_pagespeed_statistics;
pagespeed GlobalStatisticsPath /ngx_pagespeed_global_statistics;
pagespeed MessagesPath /ngx_pagespeed_message;
pagespeed ConsolePath /pagespeed_console;
pagespeed AdminPath /pagespeed_admin;
pagespeed GlobalAdminPath /pagespeed_global_admin;

server下配置

# admin頁面
location /ngx_pagespeed_statistics {
    auth_basic "PageSpeed Admin Dashboard";
    auth_basic_user_file /etc/nginx/page_speed/.htpasswd;
}
location /ngx_pagespeed_global_statistics {
    auth_basic "PageSpeed Admin Dashboard";
    auth_basic_user_file /etc/nginx/page_speed/.htpasswd;
}
location /ngx_pagespeed_message {
    auth_basic "PageSpeed Admin Dashboard";
    auth_basic_user_file /etc/nginx/page_speed/.htpasswd;
}
location /pagespeed_console {
    auth_basic "PageSpeed Admin Dashboard";
    auth_basic_user_file /etc/nginx/page_speed/.htpasswd;
}
location ~ ^/pagespeed_admin {
    auth_basic "PageSpeed Admin Dashboard";
    auth_basic_user_file /etc/nginx/page_speed/.htpasswd;
}
location ~ ^/pagespeed_global_admin {
    auth_basic "PageSpeed Admin Dashboard";
    auth_basic_user_file /etc/nginx/page_speed/.htpasswd;
}

建立用戶認證文件,/etc/nginx/page_speed/.htpasswd,使用htpasswd生成用戶名和密碼

# 建立auth用戶
htpasswd -bc .passwd archer 123456

直接訪問 <域名> /pagespeed_admin 就能夠打開管理員界面了。

提一下相關知識:

一、ngx_http_auth_basic_module模塊

ngx_http_auth_basic_module模塊實現讓訪問者,只有輸入正確的用戶密碼才容許訪問web內容。web上的一些內容不想被其餘人知道,可是又想讓部分人看到。默認狀況下nginx已經安裝了ngx_http_auth_basic_module模塊。

二、htpasswd的用法

htpasswd(選項)(參數)
-c:建立一個加密文件;
-n:不更新加密文件,只將加密後的用戶名密碼顯示在屏幕上;
-m:默認採用MD5算法對密碼進行加密;
-d:採用CRYPT算法對密碼進行加密;
-p:不對密碼進行進行加密,即明文密碼;
-s:採用SHA算法對密碼進行加密;
-b:在命令行中一併輸入用戶名和密碼而不是根據提示輸入密碼;
-D:刪除指定的用戶。

頁面相似下面這樣,咱們能夠在管理頁面,查看過濾器的效果,查看日誌,清除緩存。。。

3.4 過濾規則

過濾級別

PageSpeed提供了三個「級別」來簡化配置:PassThroughCoreFiltersOptimizeForBandwidth。CoreFilters集合包含PageSpeed團隊認爲對大多數web站點是安全的過濾器,而且是默認級別。OptimizeForBandWidth 更保守些,更安全。這裏的安全是指對原始內容的改變是否會影響頁面的展現、效果、功能等等。

這個連接有CoreFiltersOptimizeForBandwidth級別的對比,Enabling, Disabling, And Forbidding Specific Filters

CoreFilters級別包括如下過濾器

add_head
   combine_css
   combine_javascript
   convert_meta_tags
   extend_cache
   fallback_rewrite_css_urls
   flatten_css_imports
   inline_css
   inline_import_to_link
   inline_javascript
   rewrite_css
   rewrite_images
   rewrite_javascript
   rewrite_style_attributes_with_url

能夠選擇關閉或者開啓某些過濾器

# 禁用CoreFilters中的某些過濾器
pagespeed DisableFilters rewrite_images;
# 選擇性地啓用額外的過濾器
pagespeed EnableFilters collapse_whitespace;

#禁用過濾器用
pagespeed ForbidFilters rewrite_css,rewrite_javascript;
#禁用全部關閉的過濾器:
pagespeed ForbidAllDisabledFilters true;

關閉意思是不自動使用,可是咱們能夠經過輸入url參數來繼續使用該過濾器,關閉則是完全禁止,即便url參數輸入也不能使用。

能夠經過 url 參數來動態控制過濾器

例如:

http://modpagespeed.com/rewrite_css.html?PageSpeed=on&PageSpeedFilters=rewrite_css

開啓過濾器用參數 PageSpeed=on, 過濾器列表用參數 PageSpeedFilters,多個過濾器用「,」 分割。

部分配置簡介

參考: https://www.ngxpagespeed.com/

####### CSS ############
# 把多個CSS文件合併成一個CSS文件,減小 HTTP 請求數量。 
pagespeed EnableFilters combine_css; 
# combine_css配合MaxCombinedCssBytes參數使用,影響combine_css的參數
MaxBytes是組合CSS文件的最大字節大小。大於MaxBytes的CSS文件將保持完整;其餘CSS文件將被組合成一個或多個文件,每一個文件的大小都不超過MaxBytes。MaxBytes的當前默認值是-1(無限制)
pagespeed MaxCombinedJsBytes MaxBytes;


# 經過刪除 CSS 文件中的@import,減小 HTTP 請求往返次數。
pagespeed EnableFilters flatten_css_imports; 

# 最小化 css 文件,去掉多餘的空格和換行,並刪除註釋 
pagespeed EnableFilters rewrite_css; 

# 重寫CSS,首先加載渲染頁面的CSS規則 
pagespeed EnableFilters prioritize_critical_css; 

# 將小的 css 文件已內聯方式引入,避免 http 請求。
inline_css

# 將 css 內容移動到 script 以前,優先於 script 渲染。
move_css_above_scripts

#將 css 文件移到頭部。顯示優先,讓用戶體驗更好。
move_css_to_head



####### JS ############
# 啓用JavaScript庫卸載,經過自動把流行的 JavaScript 庫換成免費託管的 JavaScript 庫(好比由谷歌託管),減小帶寬使用量 
pagespeed EnableFilters canonicalize_javascript_libraries; 

# 把多個JavaScript文件合併成一個JavaScript文件,減小 HTTP 請求數量。
pagespeed EnableFilters combine_javascript; 
# combine_javascript配合MaxCombinedJsBytes參數使用,該參數是組合JavaScript文件的最大未壓縮大小(以字節爲單位)。大於MaxBytes的JavaScript文件將保持完整;其餘JavaScript文件將組合成一個或多個文件,每一個文件的大小不超過MaxBytes。MaxBytes的當前默認值是92160 (90K)。
pagespeed MaxCombinedJsBytes MaxBytes;

# 啓用JavaScript縮小機制 ,至關於rewrite_javascript_inline(內部腳本)和rewrite_javascript_external(外部腳本)
pagespeed EnableFilters rewrite_javascript; 

#將小的 js 文件已內聯方式引入,避免 http 請求。
inline_javascript


####### IMAGE ############
# 延時加載客戶端看不見的圖片 
pagespeed EnableFilters lazyload_images; 

# 啓用圖片優化機制 
pagespeed EnableFilters rewrite_images; 

#將小圖片的 http 調用轉成內聯方式調用。
inline_images

#存在多個相同的內聯圖片的話,經過 js 控制,只保留第一個內聯的數據。這樣能夠刪除重複數據,較小頁面體積。常常和 inline_images 過濾器配合使用。
dedup_inlined_images

# 自動將多張背景圖片合併成一張圖片。在處理一些圖標圖片時頗有用。
sprite_images


####### 其它 ############
# 啓用壓縮空白過濾器 
pagespeed EnableFilters collapse_whitespace; 

# 將多個 head 標籤合併成一個。 
pagespeed EnableFilters combine_heades; 

# 刪除帶默認屬性的標籤,縮小文檔大小
pagespeed EnableFilters elide_attributes; 

# 經過優化網頁資源的可緩存性,減小帶寬使用量
pagespeed EnableFilters extend_cache; 

# 移除 HTML 中的註釋
remove_comments

# 移除 HTML 屬性中的沒必要要的引號。
remove_quotes

4. 配置實例

/etc/nginx/page_speed/pagespeed_main.conf

pagespeed on;

#啓用PageSpeed Gzip請求資源,此項要求ng啓用gzip
pagespeed FetchWithGzip on;

#配置篩選項默認CoreFilters
pagespeed RewriteLevel CoreFilters;

#是否尊重原始header,爲了達到優化最大效果,官方建議不開啓
pagespeed RespectVary off;

# ···是否讓PageSpeed優化緩存時間(接管緩存控制)
pagespeed DisableRewriteOnNoTransform off;

#重寫HTML緩存頭,官方不建議關閉,默認會統計執行爲Cache-Control: no-cache, max-age=0
pagespeed ModifyCachingHeaders on;

#列出未解決的錯誤
pagespeed ListOutstandingUrlsOnError on;

# ···限制資源最大值啓用優化,默認大小16M
pagespeed MaxCacheableContentLength 16777216;

# 單個js文件最大大小,配合combine_javascript使用,該數值太小會引發js文件不合並
pagespeed MaxCombinedJsBytes 921600;

#配置共享內存元數據緩存
pagespeed CreateSharedMemoryMetadataCache "/var/cache/pagespeed/" 51200;

#配置文件高速緩存
pagespeed FileCachePath /var/cache/pagespeed;
pagespeed FileCacheSizeKb 102400;
pagespeed FileCacheCleanIntervalMs 3600000;
pagespeed FileCacheInodeLimit 500000;

# 爲了優化性能,能夠寫LRU緩存,nginx使用更少的進程,LRUCacheKbPerProcess能夠適當大點
pagespeed LRUCacheKbPerProcess 8192;
pagespeed LRUCacheByteLimit 16384;

#緩存清除,比較方便的管理方式是,經過admin頁面管理(本身能夠經過配置開啓)
pagespeed EnableCachePurge on;
pagespeed PurgeMethod PURGE;


#PageSpeed管理頁面配置
#共享內存統計
pagespeed Statistics on;
#開啓虛擬主機統計信息
pagespeed UsePerVhostStatistics on;
pagespeed StatisticsLogging on;
pagespeed StatisticsLoggingIntervalMs 60000;
pagespeed StatisticsLoggingMaxFileSizeKb 1024;
#消息緩衝區大小,默認爲0,不保留消息
pagespeed MessageBufferSize 100000;
pagespeed LogDir /var/log/pagespeed;
pagespeed StatisticsPath /ngx_pagespeed_statistics;
pagespeed GlobalStatisticsPath /ngx_pagespeed_global_statistics;
pagespeed MessagesPath /ngx_pagespeed_message;
pagespeed ConsolePath /pagespeed_console;
pagespeed AdminPath /pagespeed_admin;
pagespeed GlobalAdminPath /pagespeed_global_admin;

/etc/nginx/page_speed/pagespeed_server.conf

# 禁用CoreFilters中的某些過濾器
# pagespeed DisableFilters rewrite_images;
# 選擇性地啓用額外的過濾器
pagespeed EnableFilters remove_comments;
pagespeed EnableFilters collapse_whitespace; 
pagespeed EnableFilters prioritize_critical_css;

# 直接獲取HTTPS資源,容許自簽名證書資源,1.10版本後FetchHttps是默認開啓的
pagespeed FetchHttps enable,allow_self_signed;

# 啓用測量客戶端加載和呈現頁面所花費的時間
pagespeed EnableFilters add_instrumentation;
#預處理DNS
pagespeed EnableFilters insert_dns_prefetch;


# 確保對pagespeed優化資源的請求進入pagespeed處理程序而且沒有額外的頭部信息
location ~ "\.pagespeed\.([a-z]\.)?[a-z]{2}\.[^.]{10}\.[^.]+" {
add_header "" "";
}

# admin頁面
location /ngx_pagespeed_statistics {
    auth_basic "PageSpeed Admin Dashboard";
    auth_basic_user_file /etc/nginx/page_speed/.htpasswd;
}
location /ngx_pagespeed_global_statistics {
    auth_basic "PageSpeed Admin Dashboard";
    auth_basic_user_file /etc/nginx/page_speed/.htpasswd;
}
location /ngx_pagespeed_message {
    auth_basic "PageSpeed Admin Dashboard";
    auth_basic_user_file /etc/nginx/page_speed/.htpasswd;
}
location /pagespeed_console {
    auth_basic "PageSpeed Admin Dashboard";
    auth_basic_user_file /etc/nginx/page_speed/.htpasswd;
}
location ~ ^/pagespeed_admin {
    auth_basic "PageSpeed Admin Dashboard";
    auth_basic_user_file /etc/nginx/page_speed/.htpasswd;
}
location ~ ^/pagespeed_global_admin {
    auth_basic "PageSpeed Admin Dashboard";
    auth_basic_user_file /etc/nginx/page_speed/.htpasswd;
}

同時爲了優化動態文件,加入瞭如下命令

pagespeed LoadFromFile "https://www.archerwong.cn/public/"  "/data/gopath/src/z-blog/public/";
pagespeed LoadFromFile "https://archerwong.cn/public/"  "/data/gopath/src/z-blog/public/";
pagespeed LoadFromFileRuleMatch disallow .*; 
pagespeed LoadFromFileRuleMatch allow \.css$;
pagespeed LoadFromFileRuleMatch allow \.jpe?g$;
pagespeed LoadFromFileRuleMatch allow \.png$;
pagespeed LoadFromFileRuleMatch allow \.gif$;
pagespeed LoadFromFileRuleMatch allow \.js$;

5. 其餘

能夠根據PageSpeed Insights的評測來定向更改本身的網站。

開啓pagespeed的效果,比較直觀的是多個css文件合併成了一個請求,多個js文件也合併成了一個請求

參考

https://www.coderxing.com/nginx-pagespeed-module.html

相關文章
相關標籤/搜索