nginx下pagespeed使用詳解


1.簡介

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

2.安裝

官方安裝講解:地址

2.1腳本安裝

可以選擇使用自動腳本,可以到的一個對應的nginx版本,並且編譯了pagespeed模塊

查看該腳本的如何使用

$ 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的版本,編譯的參數,使用動態模塊


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"'

腳本運行結果 類似下面

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下,多了兩個文件夾

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 是相應的模塊

替換以前的nginx

(如果以前有yum安裝,並且還想使用以前的啟動腳本等,可以考慮替換,可以節省精力)

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

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有一個備機模式,它不會改變你網站的原有配置,只有在以下兩種情況下才會起作用

1、當你的請求帶着關於pagespeed的參數的時候,這時候會按照參數的配置返回給你響應。
2、當請求.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 就可以打開管理員界面了。

提一下相關知識:

1、ngx_http_auth_basic_module模塊

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

2、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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM