ngx_pagespeed speeds up your site and reduces page load time by automatically applying web performance best practices to pages and associated assets (CSS, JavaScript, images) without requiring you to modify your existing content or workflow. Features include:


  • Image optimization: stripping meta-data, dynamic resizing, recompression
  • CSS & JavaScript minification, concatenation, inlining, and outlining
  • Small resource inlining
  • Deferring image and JavaScript loading
  • HTML rewriting
  • Cache lifetime extension
  • and more

Nginx (pronounced engine-x) is a free, open-source, high-performance HTTP server and reverse proxy, as well as an IMAP/POP3 proxy server. Igor Sysoev started development of Nginx in 2002, with the first public release in 2004. Nginx now hosts nearly 12.18% (22.2M) of active sites across all domains. Nginx is known for its high performance, stability, rich feature set, simple configuration, and low resource consumption.

Nginx is one of a handful of servers written to address the C10K problem. Unlike traditional servers, Nginx doesn't rely on threads to handle requests. Instead it uses a much more scalable event-driven (asynchronous) architecture. This architecture uses small, but more importantly, predictable amounts of memory under load.
Even if you don't expect to handle thousands of simultaneous requests, you can still benefit from Nginx's high-performance and small memory footprint. Nginx scales in all directions: from the smallest VPS all the way up to clusters of servers.

Nginx powers several high-visibility sites, such as Netflix, Hulu, Pinterest, CloudFlare, Airbnb, WordPress.com, GitHub, SoundCloud, Zynga, Eventbrite, Zappos, Media Temple, Heroku, RightScale, Engine Yard and MaxCDN


1. Cài đặt

Trong tut này mình sẽ hướng dẫn các bạn cài đặt phiên bản nginx mới nhất là nginx 1.7.9 và ngx_pagespeed 1.9.32.2

1.1. Cài các lib cần thiết

yum -y install gcc-c++ pcre-dev pcre-devel zlib-devel make openssl-devel

1.2. Add user nginx

groupadd nginx

useradd -g nginx -d /dev/null -s /sbin/nologin nginx

1.3. Tiến hành cài đặt

Chạy lần lượt các lệnh sau

cd /opt
wget https://github.com/pagespeed/ngx_pagespeed/archive/release-1.9.32.2-beta.zip
unzip release-1.9.32.2-beta.zip
cd ngx_pagespeed-release-1.9.32.2-beta
wget https://dl.google.com/dl/page-speed/psol/1.9.32.2.tar.gz
tar -xvf 1.9.32.2.tar.gz
cd /opt
wget http://nginx.org/download/nginx-1.7.9.tar.gz
tar -xvf nginx-1.7.9.tar.gz
cd nginx-1.7.9
./configure --prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx --with-http_ssl_module --conf-path=/etc/nginx/nginx.conf --with-http_gzip_static_module --with-http_realip_module --group=nginx --user=nginx --pid-path=/var/run/nginx.pid --with-http_stub_status_module --add-module=/opt/ngx_pagespeed-release-1.9.32.2-beta
make
make install

1.4. Tạo file khởi động

Truy cập vào  /etc/init.d/ tạo file nginx với nội dung sau

#!/bin/sh
#
# nginx - this script starts and stops the nginx daemon
#
# chkconfig:   - 85 15
# description:  Nginx is an HTTP(S) server, HTTP(S) reverse \
#               proxy and IMAP/POP3 proxy server
# processname: nginx
# config:      /etc/nginx/nginx.conf
# config:      /etc/sysconfig/nginx
# pidfile:     /var/run/nginx.pid

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0

nginx="/usr/sbin/nginx"
prog=$(basename $nginx)

NGINX_CONF_FILE="/etc/nginx/nginx.conf"

[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx

lockfile=/var/lock/subsys/nginx

make_dirs() {
   # make required directories
   user=`$nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
   if [ -z "`grep $user /etc/passwd`" ]; then
       useradd -M -s /bin/nologin $user
   fi
   options=`$nginx -V 2>&1 | grep 'configure arguments:'`
   for opt in $options; do
       if [ `echo $opt | grep '.*-temp-path'` ]; then
           value=`echo $opt | cut -d "=" -f 2`
           if [ ! -d "$value" ]; then
               # echo "creating" $value
               mkdir -p $value && chown -R $user $value
           fi
       fi
   done
}

start() {
    [ -x $nginx ] || exit 5
    [ -f $NGINX_CONF_FILE ] || exit 6
    make_dirs
    echo -n $"Starting $prog: "
    daemon $nginx -c $NGINX_CONF_FILE
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}

stop() {
    echo -n $"Stopping $prog: "
    killproc $prog -QUIT
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}

restart() {
    configtest || return $?
    stop
    sleep 1
    start
}

reload() {
    configtest || return $?
    echo -n $"Reloading $prog: "
    killproc $nginx -HUP
    RETVAL=$?
    echo
}

force_reload() {
    restart
}

configtest() {
  $nginx -t -c $NGINX_CONF_FILE
}

rh_status() {
    status $prog
}

rh_status_q() {
    rh_status >/dev/null 2>&1
}

case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart|configtest)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
            ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
        exit 2
esac


- Chmod cho file nginx
chmod +x /etc/init.d/nginx
- Run tiếp các lệnh sau
mkdir -p /var/cache/ngx_pagespeed
mkdir -p /var/log/nginx
chown -R nginx:nginx /var/cache/ngx_pagespeed
chown -R nginx:nginx /var/log/nginx

- Khởi động nginx
service nginx start
chkconfig --levels 235 nginx on

2. Cấu hình

Mở file /etc/nginx/nginx.conf thay thế toàn bộ nội dung bằng


user  nginx;
worker_processes  auto;
worker_rlimit_nofile 65536;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  2048;
    use epoll;
    multi_accept on;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:15m;
   limit_req_zone $binary_remote_addr zone=req_limit_per_ip:25m rate=90r/s;
    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  off;
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    types_hash_max_size 2048;
    server_tokens off;
    server_names_hash_bucket_size 128;
    open_file_cache max=50000 inactive=30s;
    open_file_cache_valid 60s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;
    client_body_buffer_size 256k;
    client_body_timeout 12;
    client_header_buffer_size 2m;
    large_client_header_buffers 4 256k;
    client_header_timeout  2m;
    keepalive_timeout 22;
    keepalive_requests 200;
    keepalive_disable msie6;
    reset_timedout_connection on;
    send_timeout 6;
    gzip on;
    gzip_static on;
    gzip_disable "msie6";
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 3;
    gzip_buffers 16 8k;
    gzip_min_length 1024;
    gzip_http_version 1.1;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    include /etc/nginx/conf.d/*.conf;
}

- Tạo file /etc/nginx/ngx_pagespeed.conf với nội dung sau

 # PageSpeed
# Enable ngx_pagespeed
pagespeed on;
pagespeed FileCachePath /var/cache/ngx_pagespeed;

# 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 /ngx_pagespeed_statistics { allow 127.0.0.1; deny all; }
location /ngx_pagespeed_global_statistics { allow 127.0.0.1; deny all; }
location /ngx_pagespeed_message { allow 127.0.0.1; deny all; }

pagespeed MemcachedThreads 1;
pagespeed MemcachedServers "localhost:11211";
pagespeed MemcachedTimeoutUs 100000;
# Defer and minify Javascript
pagespeed EnableFilters defer_javascript;
pagespeed EnableFilters rewrite_javascript;
pagespeed EnableFilters combine_javascript;
pagespeed EnableFilters canonicalize_javascript_libraries;

# Inline and minimize css
pagespeed EnableFilters rewrite_css;
pagespeed EnableFilters fallback_rewrite_css_urls;
# Loads CSS faster
#pagespeed EnableFilters move_css_above_scripts;
pagespeed EnableFilters move_css_to_head;

# Rewrite, resize and recompress images
#pagespeed EnableFilters rewrite_images;
# pagespeed EnableFilters rewrite_images;
pagespeed DisableFilters rewrite_images;
pagespeed DisableFilters recompress_images;
pagespeed DisableFilters convert_png_to_jpeg;
pagespeed DisableFilters extend_cache_images;
# pagespeed EnableFilters convert_png_to_jpeg;
# pagespeed EnableFilters convert_jpeg_to_webp;
# pagespeed EnableFilters convert_to_webp_lossless;

# remove tags with default attributes
pagespeed EnableFilters elide_attributes;
pagespeed FetchHttps enable,allow_self_signed;

3. Tạo virtual host và thư mục public_html

- Tạo thư mục conf.d bằng lệnh sau hoặc có thể dùng winscp để tao:

mkdir -p /etc/nginx/conf.d
- Tạo thư mục public_html

mkdir -p /home/domain-của-bạn/public_html
mkdir /home/domain-của-bạn/logs
chmod 777 /domain-của-bạn/logs

- Truy cập vào thư mục conf.d và tạo một file bất kỳ với đuôi là .conf

ví dụ mình tạo file  quylevhb.conf

server {
     server_name www.domain-của-bạn;
     rewrite ^(.*) http://domain-của-bạn-không-có-www $1 permanent;
     }
server {
     listen   80;
     access_log off;
     error_log off;
     # error_log/home/domain-của-bạn/error.log;
     root /home/domain-của-bạn/public_html;
  index index.php index.html index.htm;
     server_name domain-của-bạn-không-có-www;
location / {
try_files $uri $uri/ /index.php?$args;
          }
        include /etc/nginx/ngx_pagespeed.conf;  # bật ngx_pagespeed
location ~ \.php$ {
        root  /home/domain-của-bạn/public_html;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}
}

Thay đường dẫn và server name của các bạn vào là được. Nếu các bạn muốn ghi log thì bỏ dấu # ở đoạn # error_log/home/domain-của-bạn/error.log; và sửa error_log off; thành error_log on;

- Khởi động lại nginx

service nginx restart

End tut. Tut by Quỷ lệ. Thánh nào lech vui lòng cho e xin cái nguồn.


Đăng nhận xét Blogger

 
Top