nginx静态资源缓存与压缩

一、静态资源缓存

参考文章

(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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

(2)tomcat中设置max-age或expires

首先需要引入catalina包

<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-catalina</artifactId>
    <version>7.0.61</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

注意,版本必须是7.0.61以上的,如果你不是maven需要引入jar包及相关的依赖包。 
然后找到你项目中的web.xml文件,在文件中加入如下内容

<!--设置max-age或expires-->
    <filter>
        <filter-name>ExpiresFilter</filter-name>
        <filter-class>org.apache.catalina.filters.ExpiresFilter</filter-class>
        <init-param>
            <param-name>ExpiresByType text/html</param-name>
            <param-value>access plus 1 minutes</param-value>
        </init-param>
        <init-param>
            <param-name>ExpiresByType image</param-name>
            <param-value>access plus 10 years</param-value>
        </init-param>
        <init-param>
            <param-name>ExpiresByType text/css</param-name>
            <param-value>access plus 10 months</param-value>
        </init-param>
        <init-param>
            <param-name>ExpiresByType application/javascript</param-name>
            <param-value>access plus 10 months</param-value>
        </init-param>
        <init-param>
            <param-name>ExpiresByType application/x-unknown-content-type</param-name>
            <param-value>access plus 10 years</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>ExpiresFilter</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
    </filter-mapping>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

以上内容分别对js脚本、css样式、图片以及html页面进行了缓存设置。

(3)nginx设置max-age或expires

在server节点下加入如下代码

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

这里是设置图片的过期时间为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|png){
            #这里要加上proxy_pass 否则会访问不图片
            #访问图片时会匹配这一条规则 而不是上一条
            proxy_pass http://127.0.0.1:16666;
            expires 10d;
        }


    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

(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" />
  • 1
  • 2

后台 response

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

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

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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187

这样配置以后: 
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 主进程号

posted on 2017-12-24 20:57  cn三少<script></script>  阅读(3112)  评论(0)    收藏  举报

导航