Pagespeed – это модуль Nginx, предназначенный для автоматической оптимизации работы сайта путём сокращения времени загрузки сайта в браузере.

Загрузка исходного кода и зависимостей

Для начала загружаем зависимости Nginx:

sudo apt-get build-dep nginx  

Обновляем список пакетов системы:

sudo apt-get update  

Далее, загрузим все необходимые для компиляции и тестирования программы:

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

Затем создадим в домашнем каталоге подкаталог для загрузки пакетов Nginx.

mkdir ~/custom-nginx  

Откроем его:

cd ~/custom-nginx  

Далее проверим версию Nginx

root@kvmde68-19464# nginx -v  
nginx version: nginx/1.18.0  

И загрузим исходный пакет Nginx с официального сайта.

sudo wget http://nginx.org/download/nginx-1.18.0.tar.gz  
root@kvmde68-19464:~/custom-nginx# sudo wget http://nginx.org/download/nginx-1.18.0.tar.gz  
--2020-07-02 17:22:41--  http://nginx.org/download/nginx-1.18.0.tar.gz
Resolving nginx.org (nginx.org)... 62.210.92.35, 95.211.80.227, 2001:1af8:4060:a004:21::e3  
Connecting to nginx.org (nginx.org)|62.210.92.35|:80... connected.  
HTTP request sent, awaiting response... 200 OK  
Length: 1039530 (1015K) [application/octet-stream]  
Saving to: 'nginx-1.18.0.tar.gz'  

nginx-1.18.0.tar.gz        100%[======================================>]   1015K  3.76MB/s    in 0.3s  

2020-07-02 17:22:41 (3.76 MB/s) - 'nginx-1.18.0.tar.gz' saved [1039530/1039530]  

Распакуйте полученный архив:

sudo tar zxvf nginx-1.18.0.tar.gz  

Запросите контент папки ~/custom-nginx:

ls ~/custom-nginx  

Команда покажет вывод:

root@kvmde68-19464:~/custom-nginx# ls ~/custom-nginx  
nginx-1.18.0  nginx-1.18.0.tar.gz  

Чтобы добавить модуль ngx_pagespeed, нужно сначала открыть папку modules в каталоге nginx-1.18.0:

cd nginx-1.18.0/src/http/modules/  

В этот каталог нужно загрузить архив ngx_pagespeed из репозитория Github.

sudo wget https://github.com/pagespeed/ngx_pagespeed/archive/master.zip  
root@kvmde68-19464:~/custom-nginx/nginx-1.18.0/src/http/modules# sudo wget https://github.com/pagespeed/ngx_pagespeed/archive/master.zip  
--2020-07-02 17:26:03--  https://github.com/pagespeed/ngx_pagespeed/archive/master.zip
Resolving github.com (github.com)... 140.82.113.3  
Connecting to github.com (github.com)|140.82.113.3|:443... connected.  
HTTP request sent, awaiting response... 301 Moved Permanently  
Location: https://github.com/apache/incubator-pagespeed-ngx/archive/master.zip [following]  
--2020-07-02 17:26:04--  https://github.com/apache/incubator-pagespeed-ngx/archive/master.zip
Reusing existing connection to github.com:443.  
HTTP request sent, awaiting response... 302 Found  
Location: https://codeload.github.com/apache/incubator-pagespeed-ngx/zip/master [following]  
--2020-07-02 17:26:04--  https://codeload.github.com/apache/incubator-pagespeed-ngx/zip/master
Resolving codeload.github.com (codeload.github.com)... 140.82.114.10  
Connecting to codeload.github.com (codeload.github.com)|140.82.114.10|:443... connected.  
HTTP request sent, awaiting response... 200 OK  
Length: unspecified [application/zip]  
Saving to: 'master.zip'  

master.zip                     [  <=>                                  ] 244.77K   664KB/s    in 0.4s  

2020-07-02 17:26:05 (664 KB/s) - 'master.zip' saved [250646]  

После завершения загрузки разархивируйте архив:

sudo unzip master.zip  

Для удобства переименуйте его в ngx_pagespeed:

sudo mv incubator-pagespeed-ngx-master ngx_pagespeed  

Откройте каталог:

cd ngx_pagespeed  

Загрузите в него пакет PageSpeed Optimization Libraries (psol), необходимый для компиляции:

sudo wget https://dl.google.com/dl/page-speed/psol/1.13.35.2-x64.tar.gz  
root@kvmde68-19464:~/custom-nginx/nginx-1.18.0/src/http/modules/ngx_pagespeed# sudo wget https://dl.google.com/dl/page-speed/psol/1.13.35.2-x64.tar.gz  
--2020-07-02 17:27:30--  https://dl.google.com/dl/page-speed/psol/1.13.35.2-x64.tar.gz
Resolving dl.google.com (dl.google.com)... 172.217.22.78, 2a00:1450:4001:81c::200e  
Connecting to dl.google.com (dl.google.com)|172.217.22.78|:443... connected.  
HTTP request sent, awaiting response... 200 OK  
Length: 18740791 (18M) [application/x-tar]  
Saving to: '1.13.35.2-x64.tar.gz'  

1.13.35.2-x64.tar.gz       100%[======================================>]  17.87M  12.7MB/s    in 1.4s  

2020-07-02 17:27:32 (12.7 MB/s) - '1.13.35.2-x64.tar.gz' saved [18740791/18740791]  

В завершение извлеките архив psol в каталог ngx_pagespeed:

sudo tar -xzvf 1.13.35.2-x64.tar.gz  

Настройка и компиляция исходного кода

Теперь нужно отредактировать код Nginx и добавить в него модуль pagespeed. Откройте родительский каталог кода Nginx:

cd ~/custom-nginx/nginx-1.18.0/  

Смотрим конфигурацию уже установленного nginx в системе:

# nginx -V
root@kvmde68-19464:~/custom-nginx/nginx-1.18.0# nginx -V  
nginx version: nginx/1.18.0  
built by gcc 6.3.0 20170516 (Debian 6.3.0-18+deb9u1)  
built with OpenSSL 1.1.0l  10 Sep 2019  
TLS SNI support enabled  
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-g -O2 -fdebug-prefix-map=/data/builder/debuild/nginx-1.18.0/debian/debuild-base/nginx-1.18.0=. -fstack-protector-strong -Wformat -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -Wl,--as-needed -pie'

Соберем nginx из исходников:

# sudo ./configure __параметры_у_старого_nginx_ --add-module=:
sudo ./configure --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-g -O2 -fdebug-prefix-map=/data/builder/debuild/nginx-1.18.0/debian/debuild-base/nginx-1.18.0=. -fstack-protector-strong -Wformat -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -Wl,--as-needed -pie' --add-module=./src/http/modules/ngx_pagespeed/  
root@kvmde68-19464:~/custom-nginx/nginx-1.18.0# sudo ./configure --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-g -O2 -fdebug-prefix-map=/data/builder/debuild/nginx-1.18.0/debian/debuild-base/nginx-1.18.0=. -fstack-protector-strong -Wformat -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -Wl,--as-needed -pie' --add-module=./src/http/modules/ngx_pagespeed/  
checking for OS  
 + Linux 4.9.0-12-amd64 x86_64
checking for C compiler ... found  
 + using GNU C compiler
 + gcc version: 6.3.0 20170516 (Debian 6.3.0-18+deb9u1) 
checking for gcc -pipe switch ... found  
checking for --with-ld-opt="-Wl,-z,relro -Wl,-z,now -Wl,--as-needed -pie" ... found  
checking for -Wl,-E switch ... found  
checking for gcc builtin atomic operations ... found  
checking for C99 variadic macros ... found  
checking for gcc variadic macros ... found  
checking for gcc builtin 64 bit byteswap ... found  
checking for unistd.h ... found  
checking for inttypes.h ... found  
checking for limits.h ... found  
checking for sys/filio.h ... not found  
checking for sys/param.h ... found  
checking for sys/mount.h ... found  
checking for sys/statvfs.h ... found  
checking for crypt.h ... found  
checking for Linux specific features  
checking for epoll ... found  
checking for EPOLLRDHUP ... found  
checking for EPOLLEXCLUSIVE ... found  
checking for O_PATH ... found  
checking for sendfile() ... found  
checking for sendfile64() ... found  
checking for sys/prctl.h ... found  
checking for prctl(PR_SET_DUMPABLE) ... found  
checking for prctl(PR_SET_KEEPCAPS) ... found  
checking for capabilities ... found  
checking for crypt_r() ... found  
checking for sys/vfs.h ... found  
checking for poll() ... found  
checking for /dev/poll ... not found  
checking for kqueue ... not found  
checking for crypt() ... not found  
checking for crypt() in libcrypt ... found  
checking for F_READAHEAD ... not found  
checking for posix_fadvise() ... found  
checking for O_DIRECT ... found  
checking for F_NOCACHE ... not found  
checking for directio() ... not found  
checking for statfs() ... found  
checking for statvfs() ... found  
checking for dlopen() ... not found  
checking for dlopen() in libdl ... found  
checking for sched_yield() ... found  
checking for sched_setaffinity() ... found  
checking for SO_SETFIB ... not found  
checking for SO_REUSEPORT ... found  
checking for SO_ACCEPTFILTER ... not found  
checking for SO_BINDANY ... not found  
checking for IP_TRANSPARENT ... found  
checking for IP_BINDANY ... not found  
checking for IP_BIND_ADDRESS_NO_PORT ... found  
checking for IP_RECVDSTADDR ... not found  
checking for IP_SENDSRCADDR ... not found  
checking for IP_PKTINFO ... found  
checking for IPV6_RECVPKTINFO ... found  
checking for TCP_DEFER_ACCEPT ... found  
checking for TCP_KEEPIDLE ... found  
checking for TCP_FASTOPEN ... found  
checking for TCP_INFO ... found  
checking for accept4() ... found  
checking for kqueue AIO support ... not found  
checking for Linux AIO support ... found  
checking for int size ... 4 bytes  
checking for long size ... 8 bytes  
checking for long long size ... 8 bytes  
checking for void * size ... 8 bytes  
checking for uint32_t ... found  
checking for uint64_t ... found  
checking for sig_atomic_t ... found  
checking for sig_atomic_t size ... 4 bytes  
checking for socklen_t ... found  
checking for in_addr_t ... found  
checking for in_port_t ... found  
checking for rlim_t ... found  
checking for uintptr_t ... uintptr_t found  
checking for system byte ordering ... little endian  
checking for size_t size ... 8 bytes  
checking for off_t size ... 8 bytes  
checking for time_t size ... 8 bytes  
checking for AF_INET6 ... found  
checking for setproctitle() ... not found  
checking for pread() ... found  
checking for pwrite() ... found  
checking for pwritev() ... found  
checking for sys_nerr ... found  
checking for localtime_r() ... found  
checking for clock_gettime(CLOCK_MONOTONIC) ... found  
checking for posix_memalign() ... found  
checking for memalign() ... found  
checking for mmap(MAP_ANON|MAP_SHARED) ... found  
checking for mmap("/dev/zero", MAP_SHARED) ... found  
checking for System V shared memory ... found  
checking for POSIX semaphores ... not found  
checking for POSIX semaphores in libpthread ... found  
checking for struct msghdr.msg_control ... found  
checking for ioctl(FIONBIO) ... found  
checking for ioctl(FIONREAD) ... found  
checking for struct tm.tm_gmtoff ... found  
checking for struct dirent.d_namlen ... not found  
checking for struct dirent.d_type ... found  
checking for sysconf(_SC_NPROCESSORS_ONLN) ... found  
checking for sysconf(_SC_LEVEL1_DCACHE_LINESIZE) ... found  
checking for openat(), fstatat() ... found  
checking for getaddrinfo() ... found  
configuring additional modules  
adding module in ./src/http/modules/ngx_pagespeed/  
mod_pagespeed_dir=./src/http/modules/ngx_pagespeed//psol/include  
build_from_source=false  
checking for psol ... found  
List of modules (in reverse order of applicability): ngx_http_write_filter_module ngx_http_header_filter_module ngx_http_chunked_filter_module ngx_http_v2_filter_module ngx_http_range_header_filter_module ngx_pagespeed_etag_filter ngx_http_gzip_filter_module ngx_pagespeed ngx_http_postpone_filter_module ngx_http_ssi_filter_module ngx_http_charset_filter_module ngx_http_sub_filter_module ngx_http_addition_filter_module ngx_http_gunzip_filter_module ngx_http_userid_filter_module ngx_http_headers_filter_module  
checking for psol-compiler-compat ... found  
 + ngx_pagespeed was configured
checking for PCRE library ... found  
checking for PCRE JIT support ... found  
checking for OpenSSL library ... found  
checking for zlib library ... found  
creating objs/Makefile  

Configuration summary  
  + using threads
  + using system PCRE library
  + using system OpenSSL library
  + using system zlib library

  nginx path prefix: "/etc/nginx"
  nginx binary file: "/usr/sbin/nginx"
  nginx modules path: "/usr/lib/nginx/modules"
  nginx configuration prefix: "/etc/nginx"
  nginx configuration file: "/etc/nginx/nginx.conf"
  nginx pid file: "/var/run/nginx.pid"
  nginx error log file: "/var/log/nginx/error.log"
  nginx http access log file: "/var/log/nginx/access.log"
  nginx http client request body temporary files: "/var/cache/nginx/client_temp"
  nginx http proxy temporary files: "/var/cache/nginx/proxy_temp"
  nginx http fastcgi temporary files: "/var/cache/nginx/fastcgi_temp"
  nginx http uwsgi temporary files: "/var/cache/nginx/uwsgi_temp"
  nginx http scgi temporary files: "/var/cache/nginx/scgi_temp"


Завершив настройку, запустите компиляцию:

sudo make  

file

После этого можно установить программу:

sudo make install  

После этого мы увидим что модуль добавлен:

root@kvmde68-19464:~/custom-nginx/nginx-1.18.0# nginx -V  
nginx version: nginx/1.18.0  
built by gcc 6.3.0 20170516 (Debian 6.3.0-18+deb9u1)  
built with OpenSSL 1.1.0l  10 Sep 2019  
TLS SNI support enabled  
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-g -O2 -fdebug-prefix-map=/data/builder/debuild/nginx-1.18.0/debian/debuild-base/nginx-1.18.0=. -fstack-protector-strong -Wformat -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -Wl,--as-needed -pie' --add-module=./src/http/modules/ngx_pagespeed/

Включение ngx_pagespeed

После установки сервера Nginx нужно включить модуль ngx_pagespeed.

Сначала нужно создать папку, в которой модуль будет хранить кэш файлов сайта:

sudo mkdir -p /var/ngx_pagespeed_cache  

Передайте права на эту папку пользователю Nginx, чтобы веб-сервер имел необходимый уровень доступа.

sudo chown -R www-data:www-data /var/ngx_pagespeed_cache  

Откройте главный конфигурационный файл Nginx, nginx.conf, для редактирования:

sudo nano /etc/nginx/nginx.conf  

Добавьте в блок http строки и сохраните изменения:

##
# Pagespeed Settings
##
pagespeed on;  
pagespeed FileCachePath /var/ngx_pagespeed_cache;  

Теперь файл /etc/nginx/nginx.conf выглядит так:

file

Добавьте в server-блок следующее:

#  Ensure requests for pagespeed optimized resources go to the pagespeed
#  handler and no extraneous headers get set.
location ~ "\.pagespeed\.([a-z]\.)?[a-z]{2}\.[^.]{10}\.[^.]+" { add_header "" ""; }  
location ~ "^/ngx_pagespeed_static/" { }  
location ~ "^/ngx_pagespeed_beacon" { }  

Эти параметры настраивают pagespeed для оптимизации сайтов.

Перезапустите Nginx, чтобы обновить настройки:

sudo service nginx restart  

Чтобы убедиться, что модуль ngx_pagespeed работает, запустите бинарный файл Nginx.

sudo /usr/sbin/nginx -V  

Если установка прошла успешно, модуль ngx_pagespeed появится в списке среди других пользовательских аргументов:

root@kvmde68-19464:~# sudo /usr/sbin/nginx -V  
nginx version: nginx/1.18.0  
built by gcc 6.3.0 20170516 (Debian 6.3.0-18+deb9u1)  
built with OpenSSL 1.1.0l  10 Sep 2019  
--add-module=./src/http/modules/ngx_pagespeed/

Теперь проверим, является ли модуль работающим или нет. Вы можете проверить его, выполнив следующую команду:

curl -I -p IP_вашего_сервера  

Вы должны увидеть следующий вывод:

root@kvmde68-19464:~# curl -I -p 5.187.7.109  
HTTP/1.1 200 OK  
Server: nginx  
Content-Type: text/html  
Connection: keep-alive  
Keep-Alive: timeout=60  
ETag: "29cd-5665e85740a22"  
Date: Fri, 03 Jul 2020 14:12:14 GMT  
X-Page-Speed: 1.13.35.2-0  
Cache-Control: max-age=0, no-cache  

Вы должны увидеть X-Page-Speed ​​и номер версии в выводе выше.
Это означает, что вы успешно установили Ngx_pagespeed на сервере.


Если у Вас возникли трудности в настройке или появились дополнительные вопросы, вы всегда можете обращаться в нашу службу поддержки через систему тикетов.

Обновлено 3 июля 2020 г.