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 主進程號


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM