웹사이트 검색

CentOS 7에서 Ngx_Pagespeed를 사용하여 Nginx 성능 속도 향상


Nginx [엔진 x]는 C로 작성된 무료 오픈 소스, 크로스 플랫폼, 강력한 웹 서버 및 역방향 프록시 소프트웨어입니다. 표준 IMAP/POP3 및 TCP/UDP 프록시 서버이기도 합니다. 로드 밸런서로 사용할 수 있습니다.

Nginx는 웹상의 수많은 사이트를 지원하는 잘 알려진 HTTP 서버(Apache HTTP 서버와 유사)입니다. 고성능과 안정성으로 인기가 높습니다.

사이트 속도 및 페이지 속도(페이지 로드 시간이라고도 함)를 포함하여 사이트의 사용자 경험을 향상시키려는 경우 고려해야 할 다양한 중요한 요소가 있습니다. 귀하의 사이트가 Nginx로 구동되는 경우 이 목적으로 ngx_pagespeed를 사용할 수 있습니다.

권장 읽기: Apache 서버 성능을 향상하려면 Mod_Pagespeed를 설치하세요.

Ngx_pagespeed는 사이트 속도를 향상하고 페이지 로드 시간을 줄이는 데 사용되는 무료 오픈 소스 Nginx 모듈입니다. 사용자가 사이트 콘텐츠를 보고 상호 작용하는 데 걸리는 시간이 크게 단축됩니다.

Ngx_pagespeed 기능:

  • HTTPS 및 URL 제어를 지원합니다.
  • 이미지 최적화: 메타데이터 제거, 동적 크기 조정, 재압축.
  • CSS 및 JavaScript 축소, 연결, 인라인 및 개요.
  • 작은 리소스 인라인.
  • 이미지 및 JavaScript 로딩을 연기합니다.
  • HTML 재작성.
  • 캐시 수명 연장.
  • 여러 서버 및 기타 여러 서버에 대한 구성이 가능합니다.

이 튜토리얼에서는 ngx_pagespeedNginx를 설치하고 RHEL/CentOS 7에서 전체 설치를 테스트하는 방법을 보여줍니다.

주의: Debian 및 Ubuntu 사용자는 이 가이드에 따라 Ngx_Pagespeed를 설치하여 Nginx 성능을 향상할 수 있습니다.

1단계: 소스에서 Nginx 설치

1. ngx_pagespeedNginx를 설치하려면 소스에서 컴파일해야 합니다. 먼저 이와 같은 소스에서 Nginx를 컴파일하는 데 필요한 모든 패키지를 설치하십시오.

yum install wget gcc cmake unzip gcc-c++ pcre-devel zlib-devel
OR
yum group install "Development Tools"

2. 다음으로 wget 명령을 사용하여 최신 버전의 Nginx(이 글 작성 당시 1.13.2)의 소스 파일을 구하고 다운로드한 tar 볼을 아래와 같이 추출합니다. .

mkdir ~/downloads
cd ~/downloads
wget -c https://nginx.org/download/nginx-1.13.2.tar.gz
tar -xzvf nginx-1.13.2.tar.gz

3. 다음으로 ngx_pagespeed 소스 파일을 다운로드하고 압축 파일의 압축을 풉니다.

wget -c https://github.com/pagespeed/ngx_pagespeed/archive/v1.12.34.2-stable.zip
unzip v1.12.34.2-stable.zip

4. 이제 압축을 푼 ngx_pagespeed 디렉토리로 이동하여 다음과 같이 PageSpeed 최적화 라이브러리를 가져와 Nginx를 컴파일합니다.

cd ngx_pagespeed-1.12.34.2-stable/
wget -c https://dl.google.com/dl/page-speed/psol/1.12.34.2-x64.tar.gz
tar -xvzf 1.12.34.2-x64.tar.gz

2단계: Ngx_Pagespeed를 사용하여 Nginx 구성 및 컴파일

5. 이제 nginx-1.13.2 디렉토리로 이동하고 아래 명령을 실행하여 Nginx 소스를 구성합니다.

cd ~/downloads/nginx-1.13.2
./configure --add-module=$HOME/downloads/ngx_pagespeed-1.12.34.2-stable/ --user=nobody --group=nobody --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid ${PS_NGX_EXTRA_FLAGS}

6. 다음으로 Nginx를 다음과 같이 컴파일하고 설치합니다.

make
make install

7. 설치 프로세스가 완료되면 Nginx에 필요한 모든 심볼릭 링크를 만듭니다.

ln -s /usr/local/nginx/conf/ /etc/nginx/
ln -s /usr/local/nginx/sbin/nginx /usr/sbin/nginx

3단계: SystemD용 Nginx 유닛 파일 생성

8. 다음으로 systemdCentOS 7init 시스템이므로 Nginx 유닛을 수동으로 생성해야 합니다. 그것을 위한 파일.

먼저 /lib/systemd/system/nginx.service 파일을 생성한 다음 NGINX systemd 서비스 파일을 가져와서 단위 파일 구성을 아래 파일에 붙여넣습니다.

vi /lib/systemd/system/nginx.service

Nginx를 구성하고 컴파일하는 동안 설정한 PIDFileNGINX 바이너리의 위치를 기록해 두고 아래와 같이 유닛 파일의 적절한 변수에 설정합니다. :

[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target

파일을 저장하고 닫습니다.

9. 이때 nginx 서비스를 잠시 시작하고, 아래 명령어를 실행하여 시스템 부팅시 시작되도록 활성화합니다.

systemctl start nginx
systemctl enable nginx
systemctl status nginx

4단계: Pagespeed 모듈로 Nginx 구성

10. Nginx가 설치되면 다음으로 Ngx_pagespeed 모듈을 활성화해야 합니다. 모듈이 웹 사이트의 파일을 캐시할 디렉토리를 생성하고 아래 명령을 사용하여 이 디렉토리에 대한 적절한 권한을 설정하는 것으로 시작하십시오.

mkdir -p /var/ngx_pagespeed_cache
chown -R nobody:nobody /var/ngx_pagespeed_cache

11. 이제 Ngx_pagespeed 모듈을 활성화하고 Nginx 구성 파일을 열고 아래 줄을 추가할 차례입니다.

중요: 서버에 nginx 가상 호스트를 구성한 경우 위의 pagespeed 지시문을 각 서버 블록에 추가하여 각 사이트에서 Ngx_pagespeed를 활성화하세요.

vi /etc/nginx/nginx.conf

서버 블록 내에 다음 Ngx_pagespeed 구성 줄을 추가합니다.

Pagespeed main settings

pagespeed on;
pagespeed FileCachePath /var/ngx_pagespeed_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 ~ "^/ngx_pagespeed_static/" { }
location ~ "^/ngx_pagespeed_beacon" { }

다음은 기본 가상 호스트에서 Ngx_pagespeed가 활성화된 Nginx 구성 파일의 작업 예입니다.

#user  nobody;
worker_processes  1;
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
#pid        logs/nginx.pid;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;
    sendfile        on;
    #tcp_nopush     on;
    #keepalive_timeout  0;
    keepalive_timeout  65;
    #gzip  on;
    server {
        listen       80;
        server_name  localhost; 
        #charset koi8-r;
        #access_log  logs/host.access.log  main;

        # Pagespeed main settings
        pagespeed on;
        pagespeed FileCachePath /var/ngx_pagespeed_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 ~ "^/ngx_pagespeed_static/" { }
        location ~ "^/ngx_pagespeed_beacon" { }

        location / {
            root   html;
            index  index.html index.htm;
        }
        #error_page  404              /404.html;
        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}
        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }

    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

12. 그런 다음 아래 명령을 실행하여 Nginx 구성 파일에 오류가 없는지 확인하세요. 모두 정상이면 아래 출력이 표시됩니다.

nginx -t

13. 마지막으로 변경 사항을 적용하려면 Nginx 서버를 다시 시작하세요.

systemctl restart nginx

5단계: Ngx_pagespeed로 Nginx 테스트

14. Ngx_pagespeed가 이제 Nginx와 함께 작동하는지 확인하려면 X-Page-Speed 헤더에 표시되어야 합니다.

curl -I -p http://localhost

위 헤더를 볼 수 없는 경우 11단계로 돌아가 지침에 따라 후속 단계에서 Ngx-pagespeed를 활성화하세요.

Ngx-pagespeed Github 저장소: https://github.com/pagespeed/ngx_pagespeed

그게 다야! 이 튜토리얼에서는 Ngx_pagespeed 모듈을 사용하여 Nginx를 설치 및 구성하여 사이트 성능을 최적화 및 개선하고 페이지 로드 시간을 줄이는 방법을 보여주었습니다.

Nginx 웹 서버를 보호하려면 Nginx 웹 서버의 보안, 강화 및 성능 향상을 위한 궁극적인 가이드 문서를 읽어보세요.

언제나 그렇듯이, 이 튜토리얼과 관련된 질문이나 생각이 있으면 주저하지 말고 알려주십시오.