程序員的快樂源泉
小明:"大偉,你知道Nginx嗎?"
大偉:"當(dāng)然知道,不就是個web服務(wù)器嗎?"
小明:"那你會配置Nginx 1.26.0嗎?"
大偉:"配置?不就是改改配置文件嗎,有什么難的?"
小明:"那我問你,client_body_buffer_size這個參數(shù)是干嘛的?"
大偉:"這個...好像不太清楚。"
小明:"那keepalive_timeout呢?sendfile呢?tcp_nopush呢?"
大偉:"這個...也不太清楚。"
小明:"那你就需要看看這篇Nginx 1.26.0配置指南了!"
1. Nginx簡介
Nginx是一個高性能的HTTP和反向代理服務(wù)器,也是一個IMAP/POP3/SMTP代理服務(wù)器。它具有以下特點(diǎn):
- 高性能:采用事件驅(qū)動架構(gòu),處理并發(fā)連接能力強(qiáng),單機(jī)可支持?jǐn)?shù)萬并發(fā)連接
- 高可靠性:穩(wěn)定性好,適合長時(shí)間運(yùn)行,支持熱重載配置
- 豐富的功能:支持反向代理、負(fù)載均衡、SSL/TLS、URL重寫、WebSocket、HTTP/2等
- 低內(nèi)存消耗:相比其他web服務(wù)器,內(nèi)存占用少,資源利用率高
- 易于配置:配置文件結(jié)構(gòu)清晰,易于理解和維護(hù)
- 模塊化設(shè)計(jì):支持豐富的第三方模塊,可擴(kuò)展性強(qiáng)
- 跨平臺:支持Linux、Windows、macOS等多種操作系統(tǒng)
2. Nginx 1.26.0安裝
2.1 Windows安裝
2.1.1 下載Nginx
官方下載地址:http://nginx.org/en/download.html
選擇Windows版本下載,文件名為nginx-1.26.0.zip。
2.1.2 安裝步驟
# 1. 解壓下載的文件到指定目錄,例如:C:\nginx
# 2. 打開命令提示符,進(jìn)入nginx目錄
cd C:\nginx
# 3. 啟動nginx
start nginx
# 4. 驗(yàn)證nginx是否運(yùn)行
tasklist /fi "imagename eq nginx.exe"
# 5. 測試訪問
# 在瀏覽器中訪問 http://localhost,如果看到歡迎頁面則安裝成功
2.1.3 Windows常用命令
# 啟動nginx
start nginx
# 停止nginx
nginx -s stop
# 重新加載配置
nginx -s reload
# 重新打開日志文件
nginx -s reopen
# 查看版本
nginx -v
# 查看編譯配置
nginx -V
# 測試配置文件
nginx -t
2.1.4 Windows配置文件位置
-
主配置文件:
C:\nginx\conf\nginx.conf -
日志文件:
C:\nginx\logs\ -
HTML文件:
C:\nginx\html\
2.2 Linux安裝
2.2.1 在Ubuntu/Debian上安裝
# 添加Nginx官方倉庫
curl -fsSL https://nginx.org/keys/nginx_signing.key | sudo gpg --dearmor -o /usr/share/keyrings/nginx-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] http://nginx.org/packages/ubuntu $(lsb_release -cs) nginx" | sudo tee /etc/apt/sources.list.d/nginx.list
# 更新軟件包列表
apt update
# 安裝Nginx 1.26.0
apt install nginx=1.26.0-1~$(lsb_release -cs)
# 啟動Nginx
systemctl start nginx
# 開機(jī)自啟
systemctl enable nginx
# 查看狀態(tài)
systemctl status nginx
2.2.2 在CentOS/RHEL上安裝
# 創(chuàng)建Nginx官方倉庫文件
cat > /etc/yum.repos.d/nginx.repo << 'EOF'
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
EOF
# 安裝Nginx 1.26.0
yum install nginx-1.26.0
# 啟動Nginx
systemctl start nginx
# 開機(jī)自啟
systemctl enable nginx
# 查看狀態(tài)
systemctl status nginx
2.2.3 從源碼編譯安裝
# 安裝依賴
yum install gcc pcre-devel zlib-devel openssl-devel -y
# 下載Nginx 1.26.0源碼
wget http://nginx.org/download/nginx-1.26.0.tar.gz
# 解壓
tar -zxvf nginx-1.26.0.tar.gz
# 編譯安裝
cd nginx-1.26.0
./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre
make && make install
# 創(chuàng)建系統(tǒng)服務(wù)
cat > /usr/lib/systemd/system/nginx.service << 'EOF'
[Unit]
Description=Nginx HTTP Server
After=network.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
PrivateTmp=true
[Install]
WantedBy=multi-user.target
EOF
# 啟動Nginx
systemctl start nginx
# 開機(jī)自啟
systemctl enable nginx
# 查看狀態(tài)
systemctl status nginx
2.3 驗(yàn)證安裝
在瀏覽器中訪問服務(wù)器IP地址,如果看到Nginx的默認(rèn)歡迎頁面,則安裝成功。
# 查看Nginx版本
nginx -v
輸出應(yīng)該顯示:nginx version: nginx/1.26.0
3. Nginx 1.26.0配置文件結(jié)構(gòu)
Nginx的主配置文件位于/etc/nginx/nginx.conf(Linux)或C:\nginx\conf\nginx.conf(Windows),主要包含以下部分:
- 全局配置:設(shè)置worker進(jìn)程數(shù)、錯誤日志等
- events配置:設(shè)置連接處理方式
- http配置:設(shè)置HTTP服務(wù)器相關(guān)參數(shù)
- server配置:設(shè)置虛擬主機(jī)
- location配置:設(shè)置URL路徑匹配規(guī)則
3.1 主配置文件示例
# 全局配置
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /run/nginx.pid;
# events配置
events {
worker_connections 1024;
use epoll;
multi_accept on;
}
# http配置
http {
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;
# 性能優(yōu)化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
# Gzip壓縮
gzip on;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript application/vnd.ms-fontobject application/x-font-ttf font/opentype image/svg+xml image/x-icon;
gzip_vary on;
gzip_min_length 1024;
gzip_buffers 16 8k;
gzip_http_version 1.1;
# 包含其他配置文件
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
3.2 配置文件目錄結(jié)構(gòu)
/etc/nginx/ # Linux
├── nginx.conf # 主配置文件
├── conf.d/ # 額外配置文件目錄
│ └── default.conf # 默認(rèn)虛擬主機(jī)配置
├── sites-available/ # 可用虛擬主機(jī)配置
├── sites-enabled/ # 啟用的虛擬主機(jī)配置(符號鏈接)
├── ssl/ # SSL證書目錄
└── mime.types # MIME類型配置
C:\nginx\ # Windows
├── conf\
│ └── nginx.conf # 主配置文件
├── html\ # 默認(rèn)網(wǎng)站目錄
├── logs\ # 日志文件目錄
└── temp\ # 臨時(shí)文件目錄
4. 全局配置參數(shù)詳解
4.1 user
語法:user user [group];
默認(rèn)值:nobody nobody
上下文:main
說明:定義Nginx worker進(jìn)程運(yùn)行的用戶和組。如果省略group參數(shù),則使用與user同名的組。
示例:
user nginx;
4.2 worker_processes
語法:worker_processes number | auto;
默認(rèn)值:1
上下文:main
說明:定義Nginx worker進(jìn)程的數(shù)量。推薦設(shè)置為auto,讓Nginx自動根據(jù)CPU核心數(shù)設(shè)置worker進(jìn)程數(shù)。
示例:
worker_processes auto;
4.3 worker_connections
語法:worker_connections number;
默認(rèn)值:1024
上下文:events
說明:設(shè)置每個worker進(jìn)程可以同時(shí)處理的最大連接數(shù)。最大并發(fā)連接數(shù) = worker_processes × worker_connections。
示例:
events {
worker_connections 1024;
}
4.4 error_log
語法:error_log file [level];
默認(rèn)值:error_log logs/error.log error;
上下文:main, http, mail, stream, server, location
說明:配置錯誤日志的路徑和日志級別。日志級別包括:debug、info、notice、warn、error、crit、alert、emerg。
示例:
error_log /var/log/nginx/error.log warn;
4.5 pid
語法:pid file;
默認(rèn)值:pid logs/nginx.pid;
上下文:main
說明:定義存儲Nginx主進(jìn)程ID的文件路徑。
示例:
pid /run/nginx.pid;
5. Events配置參數(shù)詳解
5.1 use
語法:use method;
默認(rèn)值:根據(jù)操作系統(tǒng)自動選擇
上下文:events
說明:指定使用的事件模型。可選值包括:
-
select:標(biāo)準(zhǔn)方法,適用于所有平臺,性能較差 -
poll:標(biāo)準(zhǔn)方法,適用于所有平臺,性能優(yōu)于select -
kqueue:高效方法,適用于FreeBSD、macOS -
epoll:高效方法,適用于Linux -
rtsig:可擴(kuò)展I/O,適用于Linux 2.6+ -
/dev/poll:高效方法,適用于Solaris 7 11/99+
示例:
events {
use epoll;
}
5.2 multi_accept
語法:multi_accept on | off;
默認(rèn)值:multi_accept off;
上下文:events
說明:如果設(shè)置為on,worker進(jìn)程將同時(shí)接受所有新連接。如果設(shè)置為off,worker進(jìn)程將一次接受一個新連接。
示例:
events {
multi_accept on;
}
6. HTTP配置參數(shù)詳解
6.1 sendfile
語法:sendfile on | off;
默認(rèn)值:sendfile off;
上下文:http, server, location, if in location
說明:啟用或禁用sendfile()系統(tǒng)調(diào)用。sendfile()可以在內(nèi)核空間直接傳輸文件,避免了數(shù)據(jù)在內(nèi)核空間和用戶空間之間的復(fù)制,提高了文件傳輸性能。
示例:
sendfile on;
6.2 tcp_nopush
語法:tcp_nopush on | off;
默認(rèn)值:tcp_nopush off;
上下文:http, server, location
說明:啟用或禁用TCP_NOPUSH套接字選項(xiàng)(FreeBSD)或TCP_CORK套接字選項(xiàng)(Linux)。當(dāng)設(shè)置為on時(shí),Nginx會嘗試一次性發(fā)送響應(yīng)頭和文件,而不是分開發(fā)送。這個選項(xiàng)通常與sendfile一起使用。
示例:
tcp_nopush on;
6.3 tcp_nodelay
語法:tcp_nodelay on | off;
默認(rèn)值:tcp_nodelay on;
上下文:http, server, location
說明:啟用或禁用TCP_NODELAY套接字選項(xiàng)。當(dāng)設(shè)置為on時(shí),禁用Nagle算法,立即發(fā)送數(shù)據(jù),而不是等待緩沖區(qū)填滿。這個選項(xiàng)對于實(shí)時(shí)應(yīng)用(如WebSocket、SSE)很重要。
示例:
tcp_nodelay on;
6.4 keepalive_timeout
語法:keepalive_timeout timeout [header_timeout];
默認(rèn)值:keepalive_timeout 75s;
上下文:http, server, location
說明:設(shè)置保持連接的超時(shí)時(shí)間。第一個參數(shù)設(shè)置服務(wù)器端保持連接打開的超時(shí)時(shí)間。第二個可選參數(shù)設(shè)置"Keep-Alive: timeout=time"響應(yīng)頭字段的值。兩個參數(shù)可以不同。
示例:
keepalive_timeout 65s;
6.5 keepalive_requests
語法:keepalive_requests number;
默認(rèn)值:keepalive_requests 1000;
上下文:http, server, location
說明:設(shè)置通過一個保持連接可以服務(wù)的最大請求數(shù)。當(dāng)達(dá)到最大請求數(shù)后,連接將被關(guān)閉。定期關(guān)閉連接是必要的,可以釋放每個連接的內(nèi)存分配。
示例:
keepalive_requests 1000;
6.6 client_body_buffer_size
語法:client_body_buffer_size size;
默認(rèn)值:client_body_buffer_size 8k|16k;
上下文:http, server, location
說明:設(shè)置讀取客戶端請求體的緩沖區(qū)大小。如果請求體超過緩沖區(qū)大小,整個請求體或其部分將被寫入臨時(shí)文件。默認(rèn)情況下,緩沖區(qū)大小等于兩個內(nèi)存頁面。在x86、其他32位平臺和x86-64上通常是8K,在其他64位平臺上通常是16K。
示例:
client_body_buffer_size 128k;
6.7 client_body_timeout
語法:client_body_timeout time;
默認(rèn)值:client_body_timeout 60s;
上下文:http, server, location
說明:定義讀取客戶端請求體的超時(shí)時(shí)間。超時(shí)時(shí)間僅在兩次連續(xù)讀取操作之間設(shè)置,而不是整個請求體的傳輸時(shí)間。如果客戶端在此時(shí)間內(nèi)不傳輸任何內(nèi)容,請求將被終止,并返回408(Request Time-out)錯誤。
示例:
client_body_timeout 60s;
6.8 client_header_buffer_size
語法:client_header_buffer_size size;
默認(rèn)值:client_header_buffer_size 1k;
上下文:http, server
說明:設(shè)置讀取客戶端請求頭的緩沖區(qū)大小。對于大多數(shù)請求,1K字節(jié)的緩沖區(qū)就足夠了。但是,如果請求包含長cookie或來自WAP客戶端,可能不適合1K。如果請求行或請求頭字段不適合此緩沖區(qū),則分配由large_client_header_buffers指令配置的更大緩沖區(qū)。
示例:
client_header_buffer_size 1k;
6.9 client_header_timeout
語法:client_header_timeout time;
默認(rèn)值:client_header_timeout 60s;
上下文:http, server
說明:定義讀取客戶端請求頭的超時(shí)時(shí)間。如果客戶端在此時(shí)間內(nèi)不傳輸整個請求頭,請求將被終止,并返回408(Request Time-out)錯誤。
示例:
client_header_timeout 60s;
6.10 client_max_body_size
語法:client_max_body_size size;
默認(rèn)值:client_max_body_size 1m;
上下文:http, server, location
說明:設(shè)置客戶端請求體的最大允許大小。如果請求中的大小超過配置的值,則向客戶端返回413(Request Entity Too Large)錯誤。請注意,瀏覽器無法正確顯示此錯誤。將size設(shè)置為0將禁用客戶端請求體大小的檢查。
示例:
client_max_body_size 10m;
6.11 large_client_header_buffers
語法:large_client_header_buffers number size;
默認(rèn)值:large_client_header_buffers 4 8k;
上下文:http, server
說明:設(shè)置用于讀取大型客戶端請求頭的最大數(shù)量和緩沖區(qū)大小。請求行不能超過一個緩沖區(qū)的大小,否則向客戶端返回414(Request-URI Too Large)錯誤。請求頭字段也不能超過一個緩沖區(qū)的大小,否則向客戶端返回400(Bad Request)錯誤。緩沖區(qū)僅在需要時(shí)分配。
示例:
large_client_header_buffers 4 32k;
7. 文件上傳與請求體限制配置詳解
7.1 client_max_body_size
語法:client_max_body_size size;
默認(rèn)值:client_max_body_size 1m;
上下文:http, server, location
說明:設(shè)置客戶端請求體的最大允許大小。如果請求體超過此限制,Nginx會返回413(Request Entity Too Large)錯誤。對于文件上傳功能,這個參數(shù)尤為重要。設(shè)置為0表示不限制。
示例:
# 允許上傳最大100MB的文件
client_max_body_size 100m;
# 或者設(shè)置為0,不限制大?。ú煌扑]用于生產(chǎn)環(huán)境)
# client_max_body_size 0;
7.2 client_body_buffer_size
語法:client_body_buffer_size size;
默認(rèn)值:client_body_buffer_size 8k|16k;
上下文:http, server, location
說明:設(shè)置讀取客戶端請求體的緩沖區(qū)大小。如果請求體小于此值,將存儲在內(nèi)存中;如果大于此值,將存儲在臨時(shí)文件中。適當(dāng)增大此值可以提高文件上傳性能。
示例:
# 設(shè)置請求體緩沖區(qū)為128KB
client_body_buffer_size 128k;
7.3 client_body_temp_path
語法:client_body_temp_path path [level1 [level2 [level3]]];
默認(rèn)值:client_body_temp_path client_body_temp;
上下文:http, server, location
說明:設(shè)置存儲客戶端請求體臨時(shí)文件的目錄路徑。當(dāng)請求體超過client_body_buffer_size時(shí),會存儲在此目錄中??梢栽O(shè)置多級子目錄來分散文件存儲。
示例:
# 設(shè)置臨時(shí)文件存儲路徑,使用兩級子目錄
client_body_temp_path /var/cache/nginx/client_temp 1 2;
7.4 client_body_in_file_only
語法:client_body_in_file_only on | clean | off;
默認(rèn)值:client_body_in_file_only off;
上下文:http, server, location
說明:設(shè)置是否總是將客戶端請求體寫入文件。當(dāng)設(shè)置為on時(shí),即使請求體很小也會寫入文件;clean表示請求處理完成后刪除文件。
示例:
# 總是將請求體寫入文件
client_body_in_file_only on;
7.5 client_body_in_single_buffer
語法:client_body_in_single_buffer on | off;
默認(rèn)值:client_body_in_single_buffer off;
上下文:http, server, location
說明:設(shè)置是否將整個客戶端請求體存儲在單個緩沖區(qū)中。啟用此選項(xiàng)可以避免磁盤I/O,但會消耗更多內(nèi)存。
示例:
# 將整個請求體存儲在單個緩沖區(qū)
client_body_in_single_buffer on;
8. 網(wǎng)速限制配置詳解
8.1 limit_rate
語法:limit_rate rate;
默認(rèn)值:limit_rate 0;
上下文:http, server, location, if in location
說明:限制向客戶端傳輸響應(yīng)的速率,單位為字節(jié)/秒。設(shè)置為0表示不限制。這個限制是針對每個連接的,如果有多個連接,總速率將是limit_rate乘以連接數(shù)。
示例:
# 限制每個連接的下載速度為100KB/s
limit_rate 100k;
# 限制每個連接的下載速度為1MB/s
limit_rate 1m;
8.2 limit_rate_after
語法:limit_rate_after size;
默認(rèn)值:limit_rate_after 0;
上下文:http, server, location, if in location
說明:設(shè)置在一定大小的數(shù)據(jù)傳輸之后才開始限速。這在允許快速下載初始數(shù)據(jù)(如網(wǎng)頁頭部)后限制大文件下載速度時(shí)非常有用。
示例:
# 先以全速傳輸500KB,之后限制為100KB/s
limit_rate_after 500k;
limit_rate 100k;
8.3 限速配置實(shí)際應(yīng)用場景
場景1:限制大文件下載速度
server {
listen 80;
server_name downloads.example.com;
location /files/ {
root /var/www/downloads;
# 對于大文件,先快速傳輸1MB,然后限制為500KB/s
limit_rate_after 1m;
limit_rate 500k;
# 允許斷點(diǎn)續(xù)傳
add_header Accept-Ranges bytes;
}
}
場景2:根據(jù)文件類型限速
server {
listen 80;
server_name example.com;
# 視頻文件限速
location ~* \.(mp4|avi|mkv)$ {
root /var/www/videos;
limit_rate 2m; # 限制為2MB/s
}
# 普通文件不限速
location ~* \.(pdf|doc|docx)$ {
root /var/www/documents;
# 不設(shè)置limit_rate,使用全速
}
}
場景3:動態(tài)限速(根據(jù)變量)
server {
listen 80;
server_name example.com;
location /download/ {
root /var/www/files;
# 根據(jù)cookie中的用戶類型設(shè)置不同限速
if ($http_cookie ~* "user_type=vip") {
set $limit_rate 5m; # VIP用戶5MB/s
}
if ($http_cookie ~* "user_type=normal") {
set $limit_rate 500k; # 普通用戶500KB/s
}
limit_rate $limit_rate;
}
}
9. Gzip壓縮配置詳解
7.1 gzip
語法:gzip on | off;
默認(rèn)值:gzip off;
上下文:http, server, location, if in location
說明:啟用或禁用gzip壓縮。啟用gzip壓縮可以顯著減少傳輸數(shù)據(jù)的大小,提高網(wǎng)站加載速度。
示例:
gzip on;
7.2 gzip_comp_level
語法:gzip_comp_level level;
默認(rèn)值:gzip_comp_level 1;
上下文:http, server, location
說明:設(shè)置gzip壓縮級別。級別從1到9,級別越高,壓縮率越高,但CPU消耗也越大。通常設(shè)置為6是一個很好的平衡點(diǎn)。
示例:
gzip_comp_level 6;
7.3 gzip_types
語法:gzip_types mime-type ...;
默認(rèn)值:gzip_types text/html;
上下文:http, server, location
說明:設(shè)置哪些MIME類型應(yīng)該被gzip壓縮。默認(rèn)情況下,只有text/html會被壓縮。
示例:
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript application/vnd.ms-fontobject application/x-font-ttf font/opentype image/svg+xml image/x-icon;
7.4 gzip_vary
語法:gzip_vary on | off;
默認(rèn)值:gzip_vary off;
上下文:http, server, location
說明:啟用或禁用響應(yīng)頭"Vary: Accept-Encoding"。當(dāng)啟用時(shí),代理緩存會根據(jù)Accept-Encoding頭進(jìn)行區(qū)分。
示例:
gzip_vary on;
7.5 gzip_min_length
語法:gzip_min_length length;
默認(rèn)值:gzip_min_length 20;
上下文:http, server, location
說明:設(shè)置啟用gzip壓縮的最小響應(yīng)長度。只有大于此長度的響應(yīng)才會被壓縮。
示例:
gzip_min_length 1024;
7.6 gzip_buffers
語法:gzip_buffers number size;
默認(rèn)值:gzip_buffers 32 4k|16 8k;
上下文:http, server, location
說明:設(shè)置用于壓縮響應(yīng)的緩沖區(qū)數(shù)量和大小。
示例:
gzip_buffers 16 8k;
7.7 gzip_http_version
語法:gzip_http_version 1.0 | 1.1;
默認(rèn)值:gzip_http_version 1.1;
上下文:http, server, location
說明:設(shè)置壓縮響應(yīng)所需的HTTP協(xié)議版本。
示例:
gzip_http_version 1.1;
10. 日志配置詳解
10.1 log_format
語法:log_format name string ...;
默認(rèn)值:log_format combined "...";
上下文:http
說明:定義日志格式。string可以包含變量。
常用變量:
-
$remote_addr:客戶端IP地址 -
$remote_user:客戶端用戶名(如果已認(rèn)證) -
$time_local:本地時(shí)間 -
$request:完整的請求行 -
$status:響應(yīng)狀態(tài)碼 -
$body_bytes_sent:發(fā)送給客戶端的字節(jié)數(shù)(不包括響應(yīng)頭) -
$http_referer:請求的來源頁面 -
$http_user_agent:客戶端用戶代理 -
$http_x_forwarded_for:客戶端真實(shí)IP地址(通過代理)
示例:
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
10.2 access_log
語法:access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
默認(rèn)值:access_log logs/access.log combined;
上下文:http, server, location, limit_except
說明:設(shè)置訪問日志的路徑、格式和緩沖參數(shù)。
示例:
access_log /var/log/nginx/access.log main;
11. 基本配置
11.1 配置靜態(tài)網(wǎng)站
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com;
index index.html index.htm;
# 訪問日志
access_log /var/log/nginx/example.com.access.log main;
error_log /var/log/nginx/example.com.error.log warn;
# 靜態(tài)文件配置
location / {
try_files $uri $uri/ =404;
expires 30d;
add_header Cache-Control "public, max-age=2592000";
}
# 處理404錯誤
error_page 404 /404.html;
location = /404.html {
internal;
}
# 處理50x錯誤
error_page 500 502 503 504 /50x.html;
location = /50x.html {
internal;
}
# 安全配置
server_tokens off;
add_header X-Content-Type-Options "nosniff";
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
}
參數(shù)說明:
-
listen:設(shè)置服務(wù)器監(jiān)聽的地址和端口 -
server_name:設(shè)置虛擬主機(jī)的域名 -
root:設(shè)置網(wǎng)站根目錄 -
index:設(shè)置默認(rèn)索引文件 -
try_files:按順序檢查文件是否存在 -
expires:設(shè)置過期時(shí)間 -
server_tokens:隱藏Nginx版本信息
11.2 配置反向代理
server {
listen 80;
server_name example.com;
access_log /var/log/nginx/example.com.access.log main;
error_log /var/log/nginx/example.com.error.log warn;
location / {
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# 代理超時(shí)設(shè)置
proxy_connect_timeout 60s;
proxy_read_timeout 60s;
proxy_send_timeout 60s;
# 代理緩沖區(qū)設(shè)置
proxy_buffers 4 32k;
proxy_buffer_size 64k;
}
# 安全配置
server_tokens off;
add_header X-Content-Type-Options "nosniff";
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
}
參數(shù)說明:
-
proxy_pass:設(shè)置后端服務(wù)器的地址 -
proxy_set_header:設(shè)置發(fā)送給后端服務(wù)器的請求頭 -
proxy_connect_timeout:設(shè)置與后端服務(wù)器建立連接的超時(shí)時(shí)間 -
proxy_read_timeout:設(shè)置從后端服務(wù)器讀取響應(yīng)的超時(shí)時(shí)間 -
proxy_send_timeout:設(shè)置向后端服務(wù)器發(fā)送請求的超時(shí)時(shí)間 -
proxy_buffers:設(shè)置讀取后端服務(wù)器響應(yīng)的緩沖區(qū)數(shù)量和大小 -
proxy_buffer_size:設(shè)置讀取后端服務(wù)器響應(yīng)頭的緩沖區(qū)大小
11.3 配置負(fù)載均衡
# 定義 upstream 服務(wù)器組
upstream backend {
# 輪詢方式(默認(rèn))
# server 127.0.0.1:8080;
# server 127.0.0.1:8081;
# 權(quán)重方式
server 127.0.0.1:8080 weight=3 max_fails=3 fail_timeout=30s;
server 127.0.0.1:8081 weight=2 max_fails=3 fail_timeout=30s;
server 127.0.0.1:8082 weight=1 max_fails=3 fail_timeout=30s;
# 健康檢查
server 127.0.0.1:8083 backup;
# 會話保持
# ip_hash;
# 最少連接數(shù)
# least_conn;
}
server {
listen 80;
server_name example.com;
access_log /var/log/nginx/example.com.access.log main;
error_log /var/log/nginx/example.com.error.log warn;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# 安全配置
server_tokens off;
add_header X-Content-Type-Options "nosniff";
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
}
參數(shù)說明:
-
weight:設(shè)置服務(wù)器的權(quán)重,權(quán)重越高,分配的請求越多 -
max_fails:設(shè)置在fail_timeout時(shí)間內(nèi)失敗的最大次數(shù) -
fail_timeout:設(shè)置失敗超時(shí)時(shí)間,在此時(shí)間內(nèi)失敗max_fails次后,服務(wù)器將被標(biāo)記為不可用 -
backup:標(biāo)記為備用服務(wù)器,只在所有主服務(wù)器都不可用時(shí)使用 -
ip_hash:根據(jù)客戶端IP地址進(jìn)行哈希,確保同一客戶端的請求總是發(fā)送到同一臺服務(wù)器 -
least_conn:將請求分配給當(dāng)前連接數(shù)最少的服務(wù)器
11.4 配置HTTPS
server {
listen 443 ssl http2;
server_name example.com;
# SSL配置
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_session_tickets off;
# HSTS配置
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
access_log /var/log/nginx/example.com.ssl.access.log main;
error_log /var/log/nginx/example.com.ssl.error.log warn;
location / {
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# 安全配置
server_tokens off;
add_header X-Content-Type-Options "nosniff";
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
}
# HTTP 重定向到 HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
參數(shù)說明:
-
ssl_certificate:設(shè)置SSL證書文件的路徑 -
ssl_certificate_key:設(shè)置SSL私鑰文件的路徑 -
ssl_protocols:設(shè)置啟用的SSL/TLS協(xié)議版本 -
ssl_prefer_server_ciphers:設(shè)置是否優(yōu)先使用服務(wù)器的密碼套件 -
ssl_ciphers:設(shè)置啟用的密碼套件 -
ssl_session_cache:設(shè)置SSL會話緩存的類型和大小 -
ssl_session_timeout:設(shè)置SSL會話的超時(shí)時(shí)間 -
ssl_session_tickets:啟用或禁用SSL會話票據(jù)
12. 高級配置
12.1 配置WebSocket支持
server {
listen 80;
server_name example.com;
location /ws {
proxy_pass http://localhost:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# WebSocket超時(shí)設(shè)置
proxy_read_timeout 3600s;
proxy_write_timeout 3600s;
}
}
參數(shù)說明:
-
proxy_http_version 1.1:設(shè)置HTTP協(xié)議版本為1.1,WebSocket需要HTTP/1.1 -
proxy_set_header Upgrade $http_upgrade:設(shè)置Upgrade頭,用于協(xié)議升級 -
proxy_set_header Connection "upgrade":設(shè)置Connection頭為upgrade -
proxy_read_timeout:設(shè)置從后端服務(wù)器讀取響應(yīng)的超時(shí)時(shí)間,WebSocket需要較長的超時(shí)時(shí)間 -
proxy_write_timeout:設(shè)置向后端服務(wù)器發(fā)送請求的超時(shí)時(shí)間,WebSocket需要較長的超時(shí)時(shí)間
12.2 配置SSE(Server-Sent Events)支持
server {
listen 80;
server_name example.com;
location /events {
proxy_pass http://localhost:8080;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# SSE超時(shí)設(shè)置
proxy_read_timeout 3600s;
# 禁用緩沖
proxy_buffering off;
proxy_cache off;
chunked_transfer_encoding off;
}
}
參數(shù)說明:
-
proxy_set_header Connection "":清空Connection頭,禁用keep-alive -
proxy_buffering off:禁用代理緩沖,確保實(shí)時(shí)傳輸 -
proxy_cache off:禁用代理緩存,確保實(shí)時(shí)傳輸 -
chunked_transfer_encoding off:禁用分塊傳輸編碼
12.3 配置限流
http {
# 定義限流 zone
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;
# 定義連接數(shù)限制 zone
limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;
server {
listen 80;
server_name example.com;
# 請求限流
location /api {
limit_req zone=mylimit burst=20 nodelay;
proxy_pass http://localhost:8080;
}
# 連接數(shù)限制
location /download {
limit_conn conn_limit_per_ip 10;
root /var/www/downloads;
}
}
}
參數(shù)說明:
-
limit_req_zone:定義限流zone,$binary_remote_addr表示客戶端IP地址,rate表示速率 -
limit_req:應(yīng)用限流規(guī)則,burst表示突發(fā)大小,nodelay表示不延遲處理 -
limit_conn_zone:定義連接數(shù)限制zone -
limit_conn:應(yīng)用連接數(shù)限制規(guī)則
12.4 配置緩存
http {
# 定義緩存路徑
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;
# 定義文件緩存
fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2 keys_zone=fastcgi_cache:10m max_size=10g inactive=60m use_temp_path=off;
server {
listen 80;
server_name example.com;
# 代理緩存
location /api {
proxy_pass http://localhost:8080;
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# 靜態(tài)文件緩存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
root /var/www/example.com;
expires 30d;
add_header Cache-Control "public, max-age=2592000";
}
}
}
參數(shù)說明:
-
proxy_cache_path:定義代理緩存的路徑和參數(shù)-
levels:設(shè)置緩存目錄的層級結(jié)構(gòu) -
keys_zone:設(shè)置共享內(nèi)存區(qū)域的名稱和大小 -
max_size:設(shè)置緩存的最大大小 -
inactive:設(shè)置緩存項(xiàng)的非活動時(shí)間 -
use_temp_path:設(shè)置是否使用臨時(shí)文件路徑
-
-
proxy_cache:啟用代理緩存 -
proxy_cache_valid:設(shè)置不同響應(yīng)碼的緩存時(shí)間
13. 常見問題及解決方案
13.1 Nginx無法啟動
問題:執(zhí)行systemctl start nginx后,Nginx無法啟動。
解決方案:
- 檢查配置文件語法:
nginx -t - 查看錯誤日志:
tail -f /var/log/nginx/error.log - 檢查端口是否被占用:
netstat -tulpn | grep 80 - 檢查權(quán)限:確保Nginx用戶有訪問配置文件和網(wǎng)站目錄的權(quán)限
- 檢查SELinux設(shè)置:如果啟用了SELinux,可能需要調(diào)整策略
13.2 403 Forbidden錯誤
問題:訪問網(wǎng)站時(shí)出現(xiàn)403 Forbidden錯誤。
解決方案:
- 檢查文件權(quán)限:確保Nginx用戶有訪問網(wǎng)站目錄的權(quán)限
- 檢查SELinux設(shè)置:如果啟用了SELinux,可能需要調(diào)整策略
- 檢查配置文件:確保root目錄設(shè)置正確
- 檢查索引文件:確保網(wǎng)站目錄中有index.html或index.htm文件
- 檢查location配置:確保location塊的訪問控制設(shè)置正確
13.3 502 Bad Gateway錯誤
問題:訪問網(wǎng)站時(shí)出現(xiàn)502 Bad Gateway錯誤。
解決方案:
- 檢查后端服務(wù)器是否運(yùn)行:
ps aux | grep backend - 檢查后端服務(wù)器端口是否可達(dá):
curl http://localhost:8080 - 檢查Nginx配置:確保proxy_pass指向正確的后端服務(wù)器
- 檢查防火墻設(shè)置:確保后端服務(wù)器端口未被防火墻阻止
- 檢查后端服務(wù)器日志:查看后端服務(wù)器是否有錯誤信息
13.4 504 Gateway Timeout錯誤
問題:訪問網(wǎng)站時(shí)出現(xiàn)504 Gateway Timeout錯誤。
解決方案:
- 檢查后端服務(wù)器響應(yīng)時(shí)間:確保后端服務(wù)器能在合理時(shí)間內(nèi)響應(yīng)
- 調(diào)整Nginx超時(shí)設(shè)置:增加proxy_connect_timeout、proxy_read_timeout和proxy_send_timeout的值
- 檢查網(wǎng)絡(luò)連接:確保Nginx服務(wù)器和后端服務(wù)器之間的網(wǎng)絡(luò)連接穩(wěn)定
- 檢查后端服務(wù)器負(fù)載:如果后端服務(wù)器負(fù)載過高,可能需要增加服務(wù)器資源
14. 命令行工具
14.1 檢查配置文件語法
nginx -t
14.2 重新加載配置
nginx -s reload
14.3 停止Nginx
nginx -s stop
14.4 查看Nginx版本
nginx -v
14.5 查看Nginx配置
nginx -V
15. 生產(chǎn)級完整配置
# 全局配置
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /run/nginx.pid;
# events配置
events {
worker_connections 1024;
use epoll;
multi_accept on;
}
# http配置
http {
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;
# 性能優(yōu)化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
# Gzip壓縮
gzip on;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript application/vnd.ms-fontobject application/x-font-ttf font/opentype image/svg+xml image/x-icon;
gzip_vary on;
gzip_min_length 1024;
gzip_buffers 16 8k;
gzip_http_version 1.1;
# 限流配置
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;
# 緩存配置
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;
# 服務(wù)器配置
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name example.com;
# SSL配置
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_session_tickets off;
# HSTS配置
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
access_log /var/log/nginx/example.com.ssl.access.log main;
error_log /var/log/nginx/example.com.ssl.error.log warn;
# 安全配置
server_tokens off;
add_header X-Content-Type-Options "nosniff";
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
# 靜態(tài)文件配置
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
root /var/www/example.com;
expires 30d;
add_header Cache-Control "public, max-age=2592000";
}
# 反向代理配置
location / {
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# 代理超時(shí)設(shè)置
proxy_connect_timeout 60s;
proxy_read_timeout 60s;
proxy_send_timeout 60s;
# 代理緩沖區(qū)設(shè)置
proxy_buffers 4 32k;
proxy_buffer_size 64k;
}
# WebSocket支持
location /ws {
proxy_pass http://localhost:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# WebSocket超時(shí)設(shè)置
proxy_read_timeout 3600s;
proxy_write_timeout 3600s;
}
# 處理404錯誤
error_page 404 /404.html;
location = /404.html {
internal;
}
# 處理50x錯誤
error_page 500 502 503 504 /50x.html;
location = /50x.html {
internal;
}
}
}
程序員的快樂結(jié)局
小明:"大偉,現(xiàn)在你會配置了嗎?"
大偉:"當(dāng)然會了!畢竟你說的這么好"
小明:"那你是不是忘了《一鍵三連》了 ..."
備注:本文檔基于Nginx 1.26.0的官方文檔,詳細(xì)介紹了Nginx的所有重要參數(shù)和配置方法,包括靜態(tài)網(wǎng)站、反向代理、負(fù)載均衡、HTTPS、WebSocket、SSE、限流、緩存等配置。Nginx的配置非常靈活,可以根據(jù)實(shí)際需求進(jìn)行調(diào)整。希望本文檔能幫助你快速掌握Nginx 1.26.0的配置技巧。
免責(zé)聲明
文章供參考,實(shí)際使用建議經(jīng)過嚴(yán)格測試后再上生產(chǎn)。
說明:目前就學(xué)習(xí)了這些,后續(xù)有新知識會持續(xù)更新或完善。