Google PageSpeed for nginx
PageSpeed는 웹 사이트 응답 시간을 높이고, 반환된 HTML을 최적화하고, 페이지 로드 시간을 줄이기 위해서 구글에서 개발된 웹 서버 모듈입니다.
ngx_pagespeed 특징은 다음과 같습니다:
- 이미지 최적화: 메타 데이터 제거, 동적 크기 조정, 재압축.
- CSS 및 JavaScript 축소, 연결, 인라이닝 및 아웃라이닝.
- 작은 리소스 인라이닝.
- 이미지와 JavaScript 로딩을 연기.
- HTML 재작성.
- 캐시 수명 연장.
Dependencies
이 문서에 따라 패키지를 컴파일하기 위해서 필요한 위존성 패키지를 먼저 설치해 줍니다:
- sudo apt-get install build-essential zlib1g-dev libpcre3 libpcre3-dev unzip uuid-dev
역시 원본 문서를 확인해야 합니다. 일부 문서는 과거의 원본 문서로부터 재작성되다 보니, ngx_pagespeed가 개발됨에 따라 의존성 패키지가 바뀌는 부분을 수정하지 않습니다. 거의 대부분 원본 문서만이 이 부분을 고쳐서 재작성됩니다.
Installing nginx with ngx_pagespeed
아쉽게도 아직은 ngx_pagespeed 모듈이 동적으로 삽입이 되지 않습니다. 그렇기 때문에 nginx에 직접 모듈을 삽입해서 컴파일해야 합니다.
Download nginx source
데비안 저장소에서 nginx 소스 패키지를 가져와야 합니다. 일반적으로, 데비안이 설치될 때에는 소스 패키지를 가져오지 않도록 설정이 되어 있습니다. 그렇기 때문에 먼저 소스 패키지 목록을 가져오도록 설정을 수정해야 합니다. 직접 /etc/apt/sources.list파일을 수정하거나, Software Updater를 실행해서 소스 패키지를 가져오도록 수정을 합니다:
- deb-src를 주석해제합니다.
이제 패키지를 제작할 적당한 디렉토리를 만들고 소스 패키지를 가져옵니다:
- sudo apt update
- mkdir nginx
- cd nginx
- apt-get source nginx
마지막으로, nginx 패키지를 제작하는 것에 필요한 의존성 패키지들을 미리 설치해 둡니다:
- sudo apt build-dep nginx
Download Pagespeed source
개발-저장소의 정보에 따라 최신 버전을 확인할 수 있습니다. 현재, 1.14.33.1-RC1이 최신 버전입니다. 릴리스 정보는 여기서 확인할 수 있습니다.
위와는 다르게 디렉토리는 별도로 생성하지 않고, 위에서 만든 nginx 디렉토리에서 그대로 작업합니다:
- NPS_VERSION=1.14.33.1-RC1
- wget https://github.com/apache/incubator-pagespeed-ngx/archive/v${NPS_VERSION}.zip
- unzip v${NPS_VERSION}.zip
- nps_dir=$(find . -name "*pagespeed-ngx-${NPS_VERSION}" -type d)
- cd "$nps_dir"
- NPS_RELEASE_NUMBER=${NPS_VERSION/beta/}
- NPS_RELEASE_NUMBER=${NPS_VERSION/stable/}
- psol_url=https://dl.google.com/dl/page-speed/psol/${NPS_RELEASE_NUMBER}.tar.gz
- [ -e scripts/format_binary_url.sh ] && psol_url=$(scripts/format_binary_url.sh PSOL_BINARY_URL)
- wget ${psol_url}
- tar -xzvf $(basename ${psol_url})
Configure nginx to build with Pagespeed
이제 데비안 패키지에서 ngx_pagespeed 모듈과 함께 컴파일하도록 데비안 패키지 제작 파일들을 일부 수정해야 합니다. 먼저 nginx 디렉토리로 이동을 합니다:
- cd nginx-1.14.0
패키지 제작 debian/rules 파일을 다음과 같이 적절히 수정합니다.
# configure flags
common_configure_flags := \
--with-cc-opt="$(debian_cflags)" \
--with-ld-opt="$(debian_ldflags)" \
--prefix=/usr/share/nginx \
--conf-path=/etc/nginx/nginx.conf \
--add-module=../../../incubator-pagespeed-ngx-1.14.33.1-RC1 \
--http-log-path=/var/log/nginx/access.log \
데비안 버전은 보통 사소한 부분이 바뀔 때에는 마지막 숫자가 증가합니다. 그리고 로컬에 설치한 것과 저장소의 버전이 같을 때에는 저장소 버전을 설치합니다. 이렇게 버전을 하게 되면, 다음 사소한 업데이트가 있을 때, 버전이 같아지기 때문에 새롭게 패키징을 해야 하는 사실을 쉽게 인식할 수 있습니다.
마찬가지로 debian/changelog를 다음을 추가합니다.
nginx (1.18.0-6.2) bullseye; urgency=medium
* add-module ngx_pagespeed
-- user <user@email.com> Sat, 30 Apr 2022 04:51:58 +0900
Build the nginx Ubuntu package and install it
이제 모든 준비가 끝났습니다. 다음과 같이 패키지를 제작합니다.
- dpkg-buildpackage -i -us -uc -b
오류가 생길 시에는 오류의 내용에 따라 적절히 수정을 한 후에, 위의 명령을 다시 내리십시요.
이제 패키지를 설치해야 하는데, 모든 패키지를 설치할 필요는 없습니다. 아마도 현재 시스템에는 nginx가 동작중이고 문제가 발생하지 않았다면, 현재 시스템에 있는 패키지만 설치하시면 됩니다. 아마도 전부를 설치하려면, 의존성 문제가 발생할 것입니다.
- dpkg -l | grep nginx
ii libnginx-mod-http-geoip ii libnginx-mod-http-image-filter ii libnginx-mod-http-lua ii libnginx-mod-http-ndk ii libnginx-mod-http-xslt-filter ii libnginx-mod-mail ii libnginx-mod-stream ii nginx ii nginx-common ii nginx-core
해당 꾸러미만 찾아서 다음과 같이 설치해줍니다:
- cd ..
- sudo dpkg -i nginx_1.18.0-6.2_all.deb nginx-common_1.18.0-6.2_all.deb nginx-core_1.18.0-6.2_amd64.deb libnginx-mod-mail_1.18.0-6.2_amd64.deb libnginx-mod-stream_1.18.0-6.2_amd64.deb libnginx-mod-http-geoip_1.18.0-6.2_amd64.deb libnginx-mod-http-image-filter_1.18.0-6.2_amd64.deb libnginx-mod-http-lua_1.18.0-6.2_amd64.deb libnginx-mod-http-ndk_1.18.0-6.2_amd64.deb libnginx-mod-http-xslt-filter_1.18.0-6.2_amd64.deb
Nginx 패키지 받기
컴파일이 귀찮은 분은 여기서 컴파일된 것을 받아서 이용하셔도 좋겠습니다.
Testing
Testing with the Nginx Command
추가한 ngx_pagespeed 모듈이 추가되었는지 확인을 합니다.
- nginx -V
nginx version: nginx/1.14.0 (Ubuntu) built with OpenSSL 1.1.0h 27 Mar 2018 TLS SNI support enabled configure arguments: --with-cc-opt='-g -O2 -fdebug-prefix-map=/home/user/Documents/packages/nginx2/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 --add-module=../../../incubator-pagespeed-ngx-v1.14.33.1-RC1 --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-1.14.31.1-RC1이 보이면 정상적으로 모듈이 동작중입니다.
Testing with Curl Command
추가된 모듈을 nginx에서 설정 /etc/ngixn/site-available/default을 변경합니다: server 마지막에 새롭게 추가하십시요.
pagespeed on;
pagespeed FileCachePath /var/ngx_pagespeed_cache;
location ~ "\.pagespeed\.([a-z]\.)?[a-z]{2}\.[^.]{10}\.[^.]+" {
add_header "" "";
}
location ~ "^/pagespeed_static/" { }
location ~ "^/ngx_pagespeed_beacon$" { }
설정에 문제가 없는지 확인을 합니다:
- sudo nginx -t
- nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
- nginx: configuration file /etc/nginx/nginx.conf test is successful
서비스를 재시작합니다:
- sudo systemctl restart nginx
마지막으로 모듈이 동작하는지 확인을 합니다:
- curl -I -L localhost
HTTP/1.1 301 Moved Permanently Server: nginx/1.14.0 (Ubuntu) Content-Type: text/html; charset=utf-8 X-Content-Type-Options: nosniff Vary: Accept-Encoding, Cookie Location: http://dawoum.duckdns.org/wiki/Main_Page Date: Wed, 09 May 2018 00:32:30 GMT X-Page-Speed: 1.14.36.1-0 Cache-Control: max-age=0, no-cache, s-maxage=1200, must-revalidate X-Varnish: 361 295078 Age: 655 Via: 1.1 varnish (Varnish/5.2) Connection: keep-alive
Nginx configuration
Pagespeed global configuration
디렉토리를 만들고, 파일을 생성합니다:
- sudo mkdir -p /etc/nginx/pagespeed
파일 /etc/nginx/pagespeed/core.conf를 다음과 같이 만듭니다:
## PageSpeed configurations
pagespeed on;
pagespeed ProcessScriptVariables on;
pagespeed FetchWithGzip on;
## PageSpeed filter settings
pagespeed RewriteLevel CoreFilters;
pagespeed RespectVary off;
pagespeed DisableRewriteOnNoTransform off;
pagespeed SupportNoScriptEnabled false;
pagespeed ModifyCachingHeaders on;
pagespeed ListOutstandingUrlsOnError on;
pagespeed MaxCacheableContentLength -1;
pagespeed FileCachePath /var/cache/pagespeed;
pagespeed FileCacheSizeKb 102400;
pagespeed FileCacheCleanIntervalMs 3600000;
pagespeed FileCacheInodeLimit 500000;
pagespeed LRUCacheKbPerProcess 1024;
pagespeed LRUCacheByteLimit 16384;
## Speed up PageSpeed by storing it in the super duper fast memcached
#pagespeed MemcachedThreads 1;
#pagespeed MemcachedServers "localhost:11211";
## Speed up PageSpeed by storing it in the super duper fast redis
#pagespeed RedisServer "localhost:6379";
#pagespeed RedisTimeoutUs 1000;
## PageSpeed admin pages configuration
pagespeed UsePerVhostStatistics on;
pagespeed Statistics on;
pagespeed StatisticsLogging on;
pagespeed StatisticsLoggingIntervalMs 60000;
pagespeed StatisticsLoggingMaxFileSizeKb 1024;
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;
## PageSpeed Cache Purge
pagespeed EnableCachePurge on;
pagespeed PurgeMethod PURGE;
pagespeed DownstreamCacheRewrittenPercentageThreshold 95;
생성된 파일을 설정 파일 /etc/nginx/nginx.conf에 포함시킵니다.
# Virtual Host Configs
##
include /etc/nginx/pagespeed/core.conf;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
Create the PageSpeed folders
PageSpeed에서 필요한 디렉토리를 만듭니다:
- sudo mkdir /var/cache/pagespeed
- sudo chown www-data:root /var/cache/pagespeed
- sudo chmod 700 /var/cache/pagespeed
- sudo mkdir /var/log/pagespeed
- sudo chown www-data /var/log/pagespeed
Create site specific PageSpeed filter
사이트에 종속적인 설정 파일들을 만듭니다:
- nano /etc/nginx/pagespeed/optimize.conf
## PageSpeed configurations pagespeed FetchHttps enable,allow_self_signed; pagespeed MaxCacheableContentLength -1; ## Resource filters include pagespeed/resource_filters.conf; ## Miscellaneous pagespeed EnableFilters add_instrumentation; pagespeed EnableFilters insert_dns_prefetch; ## Cache pagespeed EnableFilters extend_cache; pagespeed EnableFilters extend_cache_pdfs; pagespeed EnableFilters local_storage_cache; ## 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 ~ "^/pagespeed_static/" { } location ~ "^/ngx_pagespeed_beacon$ps_dollar" { } ## PageSpeed Admin paths include pagespeed/admin_ui.conf;
- nano /etc/nginx/pagespeed/admin_ui.conf
## PageSpeed Admin UI paths location /ngx_pagespeed_statistics { auth_basic "Restricted"; auth_basic_user_file mypasswd; } location /ngx_pagespeed_global_statistics { auth_basic "Restricted"; auth_basic_user_file mypasswd; } location /ngx_pagespeed_message { auth_basic "Restricted"; auth_basic_user_file mypasswd; } location /pagespeed_console { auth_basic "Restricted"; auth_basic_user_file mypasswd; } location ~ ^/pagespeed_admin { auth_basic "Restricted"; auth_basic_user_file mypasswd; } location ~ ^/pagespeed_global_admin { auth_basic "Restricted"; auth_basic_user_file mypasswd; }
- nano /etc/nginx/pagespeed/resource_filters.conf
## Text / HTML pagespeed EnableFilters combine_heads; pagespeed EnableFilters collapse_whitespace; pagespeed EnableFilters convert_meta_tags; pagespeed EnableFilters elide_attributes; pagespeed EnableFilters pedantic; pagespeed EnableFilters remove_comments; pagespeed EnableFilters remove_quotes; pagespeed EnableFilters trim_urls; ## JavaScript pagespeed EnableFilters combine_javascript; pagespeed EnableFilters canonicalize_javascript_libraries; pagespeed EnableFilters inline_javascript; ## CSS pagespeed EnableFilters outline_css; pagespeed EnableFilters combine_css; pagespeed EnableFilters inline_import_to_link; pagespeed EnableFilters inline_css; pagespeed EnableFilters inline_google_font_css; pagespeed EnableFilters move_css_above_scripts; pagespeed EnableFilters move_css_to_head; pagespeed EnableFilters prioritize_critical_css; pagespeed EnableFilters rewrite_css; pagespeed EnableFilters fallback_rewrite_css_urls; pagespeed EnableFilters rewrite_style_attributes_with_url; ## Images pagespeed EnableFilters dedup_inlined_images; pagespeed EnableFilters inline_preview_images; pagespeed EnableFilters resize_mobile_images; pagespeed EnableFilters lazyload_images; pagespeed EnableFilters inline_images; pagespeed EnableFilters convert_gif_to_png; pagespeed EnableFilters convert_jpeg_to_progressive; pagespeed EnableFilters recompress_jpeg; pagespeed EnableFilters recompress_png; pagespeed EnableFilters recompress_webp; pagespeed EnableFilters strip_image_color_profile; pagespeed EnableFilters strip_image_meta_data; pagespeed EnableFilters jpeg_subsampling; pagespeed EnableFilters convert_png_to_jpeg; pagespeed EnableFilters resize_images; pagespeed EnableFilters resize_rendered_image_dimensions; pagespeed EnableFilters convert_jpeg_to_webp; pagespeed EnableFilters convert_to_webp_lossless; pagespeed EnableFilters insert_image_dimensions; pagespeed NoTransformOptimizedImages on; pagespeed EnableFilters sprite_images;
PageSpeed 설정과 통계 페이지에 접근할 사용자와 패스워드를 만듭니다.
- sudo htpasswd -b -c /etc/nginx/mypasswd myusername 'mypassword'
여기서 "myusername"과 "mypassword"는 필요한 "사용자이름"과 "사용자암호"로 각각 바꾸십시요.
Include optimize.conf for site
PageSpeed를 삽입하고 싶은 가상 호스트, 예륻 들어 /etc/nginx/site-available/default에 포함시킵니다. 마지막 중괄호가 닫히기 전에 포함시켰습니다.
##################ngx_pagespeed start
## PageSpeed configurations
include pagespeed/optimize.conf;
#################ngx_pagespeed end
}
Test
설정에 이상이 없는지 확인을 합니다:
- sudo nginx -t
이상이 없으면, nginx 서비스를 재시작합니다.
- sudo systemctl restart nginx
PageSpeed가 관리자 페이지로 접근해서 통계 등을 확인해 봅니다:
Troubleshootings
APR does not understand this error code
이 문제는 SSL 인증서 관련해서 발생하는 것으로 알려져 있습니다. 설정 문서를 참조해서 자신의 키를 명시적으로 기록할 수 있습니다.
Extenanl Resources
- 개발 사이트 설치 문서
- https://steemit.com/kr/@chicpro/ubuntu-16-04-ngxpagespeed-nginx-deb
- https://www.howtoforge.com/tutorial/how-to-install-nginx-and-google-pagespeed-on-ubuntu-16-04/
- https://blog.stackpath.com/nginx-performance-tips-google-pagespeed
- https://blog.outsider.ne.kr/1091
- https://www.webfoobar.com/node/38
- https://www.digitalocean.com/community/tutorials/how-to-increase-pagespeed-score-by-changing-your-nginx-configuration-on-ubuntu-16-04