nginx静态资源缓存与压缩

2 篇文章 0 订阅
1 篇文章 0 订阅

一、静态资源缓存

参考文章

(1)apache设置max-age或expires

这里需要修改.htaccess文件。

<IfModule mod_headers.c>
    <FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
        Header set Cache-Control "max-age=604800, public"
    </FilesMatch>
<FilesMatch "\.(xml|txt)$">
    Header set Cache-Control "max-age=18000, public, must-revalidate"
</FilesMatch>
<FilesMatch "\.(html|htm|php|shtml)$">
    Header set Cache-Control "max-age=3600, must-revalidate"
</FilesMatch>
</IfModule>
(2)tomcat中设置max-age或expires

可参考文章:http://qin686-163-com.iteye.com/blog/287782
首先需要引入catalina包

<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-catalina</artifactId>
    <version>7.0.61</version>
</dependency>

注意,版本必须是7.0.61以上的,如果你不是maven需要引入jar包及相关的依赖包。
Filter代码

public class ResponseHeaderFilter implements Filter {  
    FilterConfig fc;   

    public void doFilter(ServletRequest req, ServletResponse res,  
            FilterChain chain) throws IOException, ServletException {  
        HttpServletResponse response = (HttpServletResponse) res;  
        // set the provided HTTP response parameters  
        for (Enumeration e = fc.getInitParameterNames(); e.hasMoreElements();) {  
            String headerName = (String) e.nextElement();  
            response.addHeader(headerName, fc.getInitParameter(headerName));  
        }  
        // pass the request/response on  
        chain.doFilter(req, response);  
    }   

    public void init(FilterConfig filterConfig) {  
        this.fc = filterConfig;  
    }   

    public void destroy() {  
        this.fc = null;  
    }   

}  

然后找到你项目中的web.xml文件,在文件中加入如下内容

<!--设置max-age或expires-->
 <filter>  
        <filter-name>NoCache</filter-name>  
        <filter-class>apis.server.common.util.ResponseHeaderFilter</filter-class>  
        <init-param>  
            <param-name>Cache-Control</param-name>  
            <param-value>no-cache, must-revalidate</param-value>  
        </init-param>  
    </filter>  
    <filter>  
        <filter-name>CacheForWeek</filter-name>  
        <filter-class>apis.server.common.util.ResponseHeaderFilter</filter-class>  
        <init-param>  
            <param-name>Cache-Control</param-name>  
            <param-value>max-age=604800, public</param-value>  
        </init-param>  
    </filter>  

<filter-mapping>  
        <filter-name>NoCache</filter-name>  
        <url-pattern>*.do</url-pattern>  
    </filter-mapping>  
    <filter-mapping>  
        <filter-name>CacheForWeek</filter-name>  
        <url-pattern>/images/*</url-pattern>  
    </filter-mapping>  
    <filter-mapping>  
        <filter-name>CacheForWeek</filter-name>  
        <url-pattern>/img/*</url-pattern>  
    </filter-mapping>  
    <filter-mapping>  
        <filter-name>CacheForWeek</filter-name>  
        <url-pattern>/icons/*</url-pattern>  
    </filter-mapping>  
    <filter-mapping>  
        <filter-name>CacheForWeek</filter-name>  
        <url-pattern>/ext/*</url-pattern>  
    </filter-mapping>  
    <filter-mapping>  
        <filter-name>CacheForWeek</filter-name>  
        <url-pattern>*.js</url-pattern>  
    </filter-mapping>  
    <filter-mapping>  
        <filter-name>CacheForWeek</filter-name>  
        <url-pattern>*.css</url-pattern>  
    </filter-mapping>   

以上内容分别对js脚本、css样式、图片以及html页面进行了缓存设置。
还有一个gzip的办法,就是在服务器压缩内容,再传给浏览器。现在主流的浏览器都支持gzip压缩,而且这些html和js文本压缩起来很厉害,基本上可以有40%的压缩率。办法在servel.xml的注释里也有写,就是在Connector元素里加上
Xml代码

compression="on"  
            compressionMinSize="2048"  
            noCompressionUserAgents="gozilla,traviata"  
            compressableMimeType="text/html,text/xml,text/javascript,text/css,text/plain"  

1) compression=”on” 打开压缩功能
2) compressionMinSize=”2048” 启用压缩的输出内容大小,这里面默认为2KB(即输出内容大于2KB才压缩)
3) noCompressionUserAgents=”gozilla, traviata” 对于以下的浏览器,不启用压缩&<60;
4) compressableMimeType=”text/html,text/xml” 压缩类型

(3)nginx设置max-age或expires

可参考文章:https://blog.csdn.net/yu12377/article/details/77875045
在server节点下加入如下代码

location  ~* \.(gif|jpg|png|bmp)$ {
    expires 10d;
}

这里是设置图片的过期时间为10天。如果你的图片基本不更新可以设置的时间长一些。

个人做的配置:

server {
        listen 6666;

        location /apis {
           rewrite ^.+apis/?(.*)$ /$1 break;
           include uwsgi_params;
           proxy_pass http://127.0.0.1:14444;
        }

        location / {
           proxy_pass http://127.0.0.1:16666;
        }

        #20170331 cache static resource
        location ~* .*\.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm)$ {
            proxy_pass http://127.0.0.1:16666;
            expires 10d;
        }

        location ~* .*\.(?:js|css)$ {
            proxy_pass http://127.0.0.1:16666;
            expires 7d;
        }

        location ~* .*\.(?:js|css)$ {
           proxy_pass http://127.0.0.1:16666;
           expires 7d;
        }

        location ~* .*\.(?:html|htm)$ {
            proxy_pass http://127.0.0.1:16666;
           add_header Cache-Control "private,no-store,no-cache,must-revalidate"; 
        }


    }

nginx location的四种类别
【=】模式: location = path,此种模式优先级最高(但要全路径匹配)
【^~】模式:location ^~ path,此种模式优先级第二高于正则;
【~ or ~*】模式:location ~ path,正则模式,优先级第三,【~】正则匹配区分大小写,【~*】正则匹配不区分大小写;
【path】模式: location path,中间什么都不加,直接跟路径表达式;
注意:一次请求只能匹配一个location,一旦匹配成功后,便不再继续匹配其余location;

(4)网上有说通过设置HTML header 或 response header来进行缓存,如下

html

<meta http-equiv="Cache-Control" content="max-age=3600"/>
<meta http-equiv="Expires" content="Mon, 18 Aug 2017 23:00:00 GMT" />

后台 response

response.addHeader("Cache-Control", "max-age=3600");
response.addHeader("Last-Modified", "Fri, 31 Mar 2017 18:29:46 GMT");

然而 尝试后 并没有发现有什么作用

2.静态资源压缩

参考文章
Nginx是一款轻量级的网页服务器、反向代理器以及电子邮件代理服务器。Nginx采用的是异步非阻塞的通信机制(epoll模型),支持更大的并发连接.所谓的epoll模型:当事件没有准备好时,就放入epoll(队列)里面。如果有事件准备好了,那么就去处 理;如果事件返回的是EAGAIN,那么继续将其放入epoll里面。从而,只要有事件准备好了,我们就去处理它,只有当所有事件都没有准备好时,才在 epoll里面等着。这样,我们就可以并发处理大量的并发了,当然,这里的并发请求,是指未处理完的请求,线程只有一个,所以同时能处理的请求当然只有一 个了,只是在请求间进行不断地切换而已,切换也是因为异步事件未准备好,而主动让出的。这里的切换是没有任何代价,你可以理解为循环处理多个准备好的事 件,事实上就是这样的。
与多线程方式相比,这种事件处理方式是有很大的优势的,不需要创建线程,每个请求占用的内存也很少,没有上下文切换, 事件处理非常的轻量级,并发数再多也不会导致无谓的资源浪费(上下文切换)。对于IIS服务器,每个请求会独占一个工作线程,当并发数上到几千时,就同时 有几千的线程在处理请求了。这对操作系统来说,是个不小的挑战:因为线程带来的内存占用非常大,线程的上下文切换带来的cpu开销很大,自然性能就上不 去,从而导致在高并发场景下性能下降严重。
Nginx通过异步非阻塞的事件处理机制,Nginx实现由进程循环处理多个准备好的事件,从而实现高并发和轻量级。
Master/Worker结构:一个master进程,生成一个或多个worker进程(网上找的图):
这里写图片描述
Master-Worker设计模式核心思想是将原来串行的逻辑并行化,并将逻辑拆分成很多独立模块并行执行。其中主要包含两个主要组件Master和Worker,Master主要用来管理worker进程,将逻辑进行拆分,拆分为互相独立的部分,将每个独立部分下发到多个Worker并行执行,向各worker进程发送信号,监控worker进程的运行状态,当worker进程退出后(异常情况下),会自动重新启动新的worker进程。
Worker主要进行实际逻辑计算,并将结果返回给Master。多个worker进程之间是对等的,他们同等竞争来自客户端的请求,各进程互相之间是独立的。一个请求,只可能在一个worker进程中处理,一个worker进程,不可能处理其它进程的请求。worker进程的个数是可以设置的,一般我们会设置与机器cpu核数一致。更多的worker数,只会导致进程来竞争cpu资源了,从而带来不必要的上下文切换。
每个worker进程都是从master进程fork过来。在master进程里面,先建立好需要listen的socket之后,然后再fork出多个worker进程,这样每个worker进程都可以去accept这个socket(当然不是同一个socket,只是每个进程的这个socket会监控在同一个ip地址与端口,这个在网络协议里面是允许的)。一般来说,当一个连接进来后,所有在accept在这个socket上面的进程,都会收到通知,而只有一个进程可以accept这个连接,其它的则accept失败。
下面我个人采用Nginx实现压缩以及缓存静态资源文件,来提高服务器的请求效率,配置文件如下,具体的都在注释中体现:

<pre name="code" class="html">#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;

    ##缓存cache参数配置##
    proxy_connect_timeout 5;
    proxy_read_timeout 60;
    proxy_send_timeout 5;
    proxy_buffer_size 16k;
    proxy_buffers 4 64k;
    proxy_busy_buffers_size 128k;
    proxy_temp_file_write_size 128k;
    #缓存到nginx的本地目录
    proxy_temp_path  /Users/heyongjian/Desktop/heyongjian/FSvcWeb/nginx/temp/;
    proxy_cache_path /Users/heyongjian/Desktop/heyongjian/FSvcWeb/nginx/temp/cache_temp levels=1:2 keys_zone=cache_one:200m inactive=1d max_size=30g;
    ##end##

    #压缩配置#
    gzip  on;           #打开gzip压缩功能
    gzip_min_length 1k; #压缩阈值
    gzip_buffers 4 16k; #buffer 不用修改
    gzip_comp_level 2;  #压缩级别:1-10,数字越大压缩的越好,时间也越长
    gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;  #        压缩文件类型
    gzip_vary off;      #跟Squid等缓存服务有关,on的话会在Header里增加 "Vary: Accept-Encoding"
    gzip_disable "MSIE [1-6]\.";  #IE1-6版本不支持gzip压缩

    #具体的服务器地址及端口号,该处可以配置集群实现负载均衡,cluster为服务器集群名
    upstream cluster{
        server 10.16.39.12:8080; #并且可以分配权重weight,这样来配置集群服务器的访问优先权
        #...
    }


    server {
        listen       80;
        #nginx服务器,即代理服务器名
        server_name   localhost;

        rewrite ^(.*)$ https://$host$1 permanent; #这里是http跳转https
        #charset koi8-r;

        #access_log  logs/host.access.log  main;


         #缓存相应的文件(静态文件)
         location ~ \.(gif|jpg|png|htm|html|css|js|flv|ico|swf)(.*) {
             proxy_pass http://cluster;         #如果没有缓存则通过proxy_pass转向请求
             proxy_redirect off;
             proxy_set_header Host $host;
             proxy_cache cache_one;
             proxy_cache_valid 200 302 1h;                              #对不同的HTTP状态码设置不同的缓存时间,h小时,d天数
             proxy_cache_valid 301 1d;
             proxy_cache_valid any 1m;
             expires 30d;
       }

        #动态请求代理给相应服务器
        location / {
            proxy_pass http://cluster; 
            proxy_redirect    off;
            proxy_set_header Host  $host;
            proxy_set_header X-Forwarded-For  $remote_addr; 
       }

       #purge插件缓存清理
       location ~ /purge(/.*) {
               allow              127.0.0.1;        #能够清除缓存的服务器IP地址
               #allow             10.16.39.12;
               deny               all;
               proxy_cache_purge  cache_one $1$is_args$args;
        }
        #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;
    #    }
    #}


    #代理http跳转https这块配置
    # HTTPS server
    #
    server {
        listen       443 ssl;
        server_name  localhost;
          ssl on;

        ### SSL log files ###  
        access_log      logs/ssl-access.log;  
        error_log       logs/ssl-error.log;

        ### SSL cert files ###  
        ssl_certificate      ../../cert/server.crt;  
        ssl_certificate_key  ../../cert/server.key;

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

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

        location / {
                proxy_pass http://cluster; 
                ### force timeouts if one of backend is died ##  
                proxy_next_upstream error timeout invalid_header http_500 http_502 http_503;  

                ### Set headers ####  
                proxy_set_header Host $host;  
                proxy_set_header X-Real-IP $remote_addr;  
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  

                ### Most PHP, Python, Rails, Java App can use this header ###  
                proxy_set_header X-Forwarded-Proto https;  

                ### By default we don't want to redirect it ####  
                proxy_redirect     off;  
        }
    }

}

这样配置以后:
1.http会直接跳转https;
2.访问web应用时,静态文件会被压缩,而且能压缩到原来的30%,效果很明显;
3.第一次访问web应用时,静态文件会被缓存到指定的Nginx本地目录,再次访问时,就不会需要再次请求服务器;
4.使用ngx_cache_purge(https://github.com/FRiCKLE/ngx_cache_purge)模块进行缓存清理,例如:www.wolfdream.cn/purge/xxx.jpg 就可以清除xxx图片缓存了,另外超时的缓存Nginx会自动删除。
通过Nginx进行调优,可以使访问效率提高很多,上述若有错误,欢迎拍砖指出!

三、nginx指令

参考文章

nginx -s reload  :修改配置后重新加载生效
nginx -s reopen  :重新打开日志文件
nginx -t -c /path/to/nginx.conf 测试nginx配置文件是否正确

关闭nginx:
nginx -s stop  :快速停止nginx
         quit  :完整有序的停止nginx

其他的停止nginx 方式:

ps -ef | grep nginx

kill -QUIT 主进程号     :从容停止Nginx
kill -TERM 主进程号     :快速停止Nginx
pkill -9 nginx          :强制停止Nginx



启动nginx:
nginx -c /path/to/nginx.conf

平滑重启nginx:
kill -HUP 主进程号
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值