884天前2018-09-28 10:09:45 |    抢沙发  389 
如果我们的前端不是专业且有seo经验的开发者开发的话,会出现很多问题,比如cs,js未经压缩,一个页面调用多个cs,js文件,这样大大拉低 了页面的加载速度,因为没加载一个文件都要进行三次握手,这个速度是比较慢的。如果你也碰到了这样的站点要进行优化怎么办呢?不要慌请跟随静心一起请出ngx_pagespeed神器。

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.9
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

开工:

安装编译环境
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一下看看是否安装成功 /opt/rh/


设置变量:(根据自己的实际安装路径进行设置)


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/
到这里插件就已经配置好了,接下来就是要安装nginx并把插件添加进去了。



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


nginx添加到系统服务:


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
案例:



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;
}
到这里咱们的前端神器插件ngx_pagespeed就已经成功的集成到了nginx中,而且自带前端缓存功能,是不是很屌,赶紧试试吧,让你的网站飞起来吧。



发表评论

暂无评论

登录

忘记密码 ?

切换登录

注册

扫一扫二维码分享