Alex的博客

本博客的文章均为原创,是本人从事行业多年来所遇见一些小问题的解决心得,希望可以帮助到大家!



centos6 nginx+ngx_pagespeed 前端优化

直接上干货吧

ngx_pagespeed模块的主要功能大致有:
1)图像优化:剥离元数据、动态调整,重新压缩
2)CSS和JavaScript压缩、合并、级联、内联
3)小资源内联
4)推迟图像和JavaScript加载
5)对HTML重写、压缩空格、去除注释等
6)提升缓存周期

作为Nginx组件,ngx_pagespeed将重写你的网页,让用户以更快的速度进行访问。重写的工作包括压缩图片、缩减CSS和JavaScript、扩展缓存时间,同样还包括其它一些最佳实践:
1)优化缓存----整合应用程序的数据和逻辑
2)最小化round-trip次数----削减连续的请求/响应周期数
3)最小化请求开销----削减上传大小
4)最小化负载大小----削减响应、下载及缓存页面大小
5)优化浏览器渲染----改善浏览器页面布局
6)移动方面的优化----优化站点移动网络和设备方面的相关特性

环境介绍:

nginx1.2 稳定版本 编译安装

php7.1 yum安装

系统 centos6

nginx 下载地址:

http://nginx.org/download/nginx-1.12.2.tar.gz

ngx_pagespeed下载地址:最好根据自己nginx版本选择下载版本 因为我用的是nginx1.2 所有我下载的是稳定版 v1.12.34.3-stable 如果下载最新的会报错无法编译这个好像是由于centos6系统内核的原因  如果是7 的话可以下载最新稳定版

https://github.com/apache/incubator-pagespeed-ngx/releases


配置官方说明地址:

https://www.modpagespeed.com/doc/configuration


官方安装说明地址:

https://www.modpagespeed.com/doc/build_ngx_pagespeed_from_source


1,安装编译环境

yum install gcc-c++ pcre-devel zlib-devel make unzip libuuid-devel


rpm --import https://linux.web.cern.ch/linux/scientific6/docs/repository/cern/slc6X/i386/RPM-GPG-KEY-cern
wget -O /etc/yum.repos.d/slc6-devtoolset.repo https://linux.web.cern.ch/linux/scientific6/docs/repository/cern/devtoolset/slc6-devtoolset.repo
yum install devtoolset-2-gcc-c++ devtoolset-2-binutils

可以ls一下看看是否安装成功

PS_NGX_EXTRA_FLAGS="--with-cc=/opt/rh/devtoolset-2/root/usr/bin/gcc"

wget  https://github.com/apache/incubator-pagespeed-ngx/archive/v1.12.34.3-stable.tar.gz

tar -xzvf v1.12.34.3-stable.tar.gz

cd incubator-pagespeed-ngx-1.12.34.3-stable/

NPS_VERSION=1.12.34.3-stable

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})

cd ..

cp -rf incubator-pagespeed-ngx-1.12.34.3-stable /software/

wget http://nginx.org/download/nginx-1.12.2.tar.gz

tar -xzvf nginx-1.12.2.tar.gz

cd nginx-1.12.2

./configure --user=nginx --group=nginx --prefix=/software/nginx-1.12.2/ --with-http_v2_module --with-http_ssl_module --with-http_gzip_static_module --with-http_stub_status_module  --add-module=/software/incubator-pagespeed-ngx-1.12.34.3-stable ${PS_NGX_EXTRA_FLAGS}

make

make install


ln -s /software/nginx-1.12.2/ /software/nginx

cd /software/nginx-1.12.2/sbin/


./nginx -t

./nginx

nginx -V

添加到系统服务


vi /etc/rc.d/init.d/nginx
#!/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:      /software/nginx/conf/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="/software/nginx/sbin/nginx"
prog=$(basename $nginx)

NGINX_CONF_FILE="/software/nginx/conf/nginx.conf"

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

lockfile=/var/lock/subsys/nginx

start() {
    [ -x $nginx ] || exit 5
    [ -f $NGINX_CONF_FILE ] || exit 6
    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
killall -9 nginx
}

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 +x /etc/rc.d/init.d/nginx

chkconfig --add nginx
chkconfig --level 235 nginx on

chkconfig --list nginx

添加pagespeed配置文件

vi /software/nginx/conf/pagespeed.conf

# 启用ngx_pagespeed
pagespeed on;
pagespeed FileCachePath /software/var_temp/nginx/pagespeed/;
# 禁用CoreFilters
pagespeed RewriteLevel PassThrough;
# 启用压缩空白过滤器
pagespeed EnableFilters collapse_whitespace;
# 启用JavaScript库卸载
pagespeed EnableFilters canonicalize_javascript_libraries;
# 把多个CSS文件合并成一个CSS文件
pagespeed EnableFilters combine_css;
# 把多个JavaScript文件合并成一个JavaScript文件
pagespeed EnableFilters combine_javascript;
# 删除带默认属性的标签
pagespeed EnableFilters elide_attributes;
# 改善资源的可缓存性
pagespeed EnableFilters extend_cache;
# 更换被导入文件的@import,精简CSS文件
pagespeed EnableFilters flatten_css_imports;
pagespeed CssFlattenMaxBytes 5120;
# 延时加载客户端看不见的图片
pagespeed EnableFilters lazyload_images;
# 启用JavaScript缩小机制
pagespeed EnableFilters rewrite_javascript;
# 启用图片优化机制
pagespeed EnableFilters rewrite_images;
# 预解析DNS查询
pagespeed EnableFilters insert_dns_prefetch;
# 重写CSS,首先加载渲染页面的CSS规则
pagespeed EnableFilters prioritize_critical_css;
# Example 禁止pagespeed 处理/ipython/目录 可选
#pagespeed Disallow"*/ipython/*";


location ~ "\.pagespeed\.([a-z]\.)?[a-z]{2}\.[^.]{10}\.[^.]+" {
        add_header "" "";
        }
        location ~ "^/pagespeed_static/" { }
        location ~ "^/ngx_pagespeed_beacon$" { }


然后在需要使用 pagespeed的虚拟主机的server段里面加上
include /software/nginx/conf/pagespeed.conf


顺便贴一下我的nginx.conf 优化吧


user  nginx;
worker_processes  8;
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;
worker_rlimit_nofile 65535;
#error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    use epoll;
    worker_connections  65535;
}


http {

server_tokens off;

#禁止未绑定域名访问
server {
    listen       80  default_server;
    server_name  _;
    return       404;
}


    include       /etc/nginx/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  /var/log/nginx/access.log  main;

    sendfile        on;
    tcp_nopush     on;


keepalive_timeout 60;
client_header_timeout 15;
client_body_timeout 60s;
send_timeout 25s;
client_header_buffer_size 4k;
open_file_cache max=65535 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 1;
#limit_conn_zone $binary_remote_addr zone=addr:10m;

tcp_nodelay on;
gzip on;
gzip_min_length   1k;
gzip_buffers     4 16k;
gzip_http_version 1.1;
gzip_comp_level 7;
#gzip_types text/plain application/x-javascript text/css application/xml;
gzip_types  text/css text/xml application/javascript;
gzip_vary on;

#proxy_cache_path /var/cache/nginx/cache levels=1:2 keys_zone=imgcache:1024m inactive=1d max_size=3g;
#proxy_cache_key "$host$request_uri";
#fastcgi_cache_path /var/nginx/fastcgi_cache levels=1:2  keys_zone=TEST:10m   inactive=5m;
#fastcgi_cache_key "$scheme$request_method$host$request_uri";

fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 16k;
fastcgi_buffers 16 16k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 246k;
#fastcgi_cache fastcgi_cache;
#fastcgi_cache_key $request_method://$host.$request_uri;
#fastcgi_cache_path /var/cache/fastcgi_cache vevels:2:2 keys_zone=ngx_fcgi_cache:512m inactive=1d max_size=40g;
#fastcgi_cache_valid 200 302 1h;
#fastcgi_cache_valid 301 1d;
#fastcgi_cache_valid any 1m;
#fastcgi_cache_min_uses 1;
#fastcgi_cache_use_stale error timeout invalid_header http_500;




include /etc/nginx/conf.d/sites-enabled/*.conf;
#    include /etc/nginx/conf.d/*.conf;
}




浏览391  评论0  Alex于 2018-1-21 13:38
发言