傳統(tǒng)的web項(xiàng)目,一般都將靜態(tài)資源連同項(xiàng)目部署在容器中(如tomcat、jetty),但是有時(shí)需要把這些靜態(tài)資源文件單獨(dú)拿出來,ngnix這時(shí)可以來充當(dāng)靜態(tài)資源服務(wù)器的功能。
靜態(tài)資源web服務(wù)
靜態(tài)資源就是非服務(wù)器動(dòng)態(tài)生成的文件,主要有:

image.png

image.png
靜態(tài)資源服務(wù)場(chǎng)景-CDN

image.png
靜態(tài)資源核心配置
1. 文件讀取 sendfile
- sendfile 是一種高效傳輸文件的模式.
sendfile設(shè)置為on表示啟動(dòng)高效傳輸文件的模式。sendfile可以讓Nginx在傳輸文件時(shí)直接在磁盤和tcp socket之間傳輸數(shù)據(jù)。如果這個(gè)參數(shù)不開啟,會(huì)先在用戶空間(Nginx進(jìn)程空間)申請(qǐng)一個(gè)buffer,用read函數(shù)把數(shù)據(jù)從磁盤讀到cache,再?gòu)腸ache讀取到用戶空間的buffer,再用write函數(shù)把數(shù)據(jù)從用戶空間的buffer寫入到內(nèi)核的buffer,最后到tcp socket。開啟這個(gè)參數(shù)后可以讓數(shù)據(jù)不用經(jīng)過用戶buffer。
文件讀取配置
sendfile

image.png
syntax: sendfile on | off;
default:sendfile off
context:http,server,location,if in location
2. tcp_nopush

image.png
- 在 sendfile 開啟的情況下,提高網(wǎng)絡(luò)數(shù)據(jù)包的傳輸效率。
tcp_nopush指令,在連接套接字時(shí)啟用Linux系統(tǒng)下的TCP_CORK。該選項(xiàng)告訴TCP堆棧附加數(shù)據(jù)包,并在它們已滿或當(dāng)應(yīng)用程序通過顯式刪除TCP_CORK指示發(fā)送數(shù)據(jù)包時(shí)發(fā)送它們。 這使得發(fā)送的數(shù)據(jù)分組是最優(yōu)量,并且因此提高了網(wǎng)絡(luò)數(shù)據(jù)包的傳輸效率。
也就是說 tcp_nopush=on 時(shí),結(jié)果就是數(shù)據(jù)包不會(huì)馬上傳送出去,等到數(shù)據(jù)包最大時(shí),一次性的傳輸出去,這樣有助于解決網(wǎng)絡(luò)堵塞,雖然有一點(diǎn)點(diǎn)延遲。
配置
Syntax: tcp_nopush on | off;
Default: tcp_nopush off;
Context: http, server, location
3. tcp_nodelay

image.png
在 keepalive 連接下,提高網(wǎng)絡(luò)數(shù)據(jù)包的傳輸實(shí)時(shí)性。
tcp_nodelay選項(xiàng)和tcp_nopush正好相反,數(shù)據(jù)包不等待,實(shí)時(shí)發(fā)送給用戶。
配置:
Syntax: tcp_nodelay on | off;
Default: tcp_nodelay off;
Context: server, location
4. 壓縮

image.png
開啟壓縮,可以加快資源響應(yīng)速度,同時(shí)節(jié)省網(wǎng)絡(luò)帶寬資源。

image.png
開啟關(guān)閉壓縮:
Syntax: gzip on | off;
Default: gzip off;
Context: http, server, location, if in location
配置壓縮比,壓縮等級(jí)配置(壓縮等級(jí)越高,越消耗服務(wù)器資源)
Syntax: gzip_comp_level level;
Default: gzip_comp_level 1;
Context: http, server, location
gzip協(xié)議版本配置
Syntax: gzip_http_version 1.0 | 1.1;
Default: gzip_http_version 1.1;
Context: http, server, location
壓縮擴(kuò)展模塊
預(yù)讀gzip功能 ngx_http_gzip_static_module
Syntax: gzip_static on | off | always;
Default: gzip_static off;
Context: http, server, location
應(yīng)用支持gunzip的壓縮方式 ngx_http_gunzip_module
Syntax: gunzip on | off;
Default: gunzip off;
Context: http, server, location
Syntax: gunzip_buffers number size;
Default: gunzip_buffers 32 4k|16 8k;
Context: http, server, location
5.緩存
緩存:http協(xié)議定義的緩存機(jī)制(如:expires,cache-control 等)

image.png
無緩存情況:

image.png

image.png

image.png
配置:
syntax: expires [modified] time;
expires epoch | max | off;
default: expires off;
context:http, server, location