Nginx 配置示例及核心模塊詳解
Nginx 配置詳解
一、配置文件結(jié)構(gòu)
# 全局塊(主配置)
main
# 事件塊
events {
...
}
# HTTP 塊
http {
# HTTP 全局配置
...
# 虛擬主機(jī)塊(一個(gè)或多個(gè))
server {
# 服務(wù)器配置
...
# 位置塊(一個(gè)或多個(gè))
location {
...
}
}
# 可包含其他配置文件
include /etc/nginx/conf.d/*.conf;
}二、核心模塊詳解
1. 全局配置(main context)
user nginx nginx; # 運(yùn)行用戶和組 worker_processes auto; # 工作進(jìn)程數(shù)(auto = CPU核心數(shù)) error_log /var/log/nginx/error.log warn; # 錯(cuò)誤日志 pid /var/run/nginx.pid; # PID文件 worker_rlimit_nofile 65535; # 文件描述符限制
2. 事件模塊(events context)
events {
worker_connections 1024; # 每個(gè)worker最大連接數(shù)
use epoll; # 事件驅(qū)動模型(Linux)
multi_accept on; # 同時(shí)接受多個(gè)連接
accept_mutex off; # 連接互斥鎖
}3. HTTP模塊(http context)
基礎(chǔ)配置:
http {
include /etc/nginx/mime.types; # MIME類型
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;
# 基礎(chǔ)參數(shù)
sendfile on; # 高效文件傳輸
tcp_nopush on; # TCP優(yōu)化
tcp_nodelay on; # 禁用Nagle算法
keepalive_timeout 65; # 長連接超時(shí)
client_max_body_size 20m; # 最大上傳文件大小
# Gzip壓縮
gzip on;
gzip_comp_level 6;
gzip_types text/plain text/css application/json;
# 上游服務(wù)器(負(fù)載均衡)
upstream backend {
server 192.168.1.100:8080 weight=3;
server 192.168.1.101:8080;
server 192.168.1.102:8080 backup;
# 負(fù)載均衡策略:輪詢(默認(rèn))、ip_hash、least_conn
}
}4. 虛擬主機(jī)(server context)
server {
listen 80; # 監(jiān)聽端口
listen [::]:80 ipv6only=on; # IPv6
server_name example.com www.example.com; # 域名
# 根目錄和索引
root /var/www/html;
index index.html index.htm index.php;
# 字符集
charset utf-8;
# SSL配置(HTTPS)
listen 443 ssl http2;
ssl_certificate /etc/ssl/cert.pem;
ssl_certificate_key /etc/ssl/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
# 重定向HTTP到HTTPS
if ($scheme != "https") {
return 301 https://$host$request_uri;
}
# 安全頭
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
}5. 位置塊(location context)
location / {
# 匹配所有請求
try_files $uri $uri/ /index.php?$query_string;
}
# 精確匹配(=)
location = /api {
# 僅匹配 /api
}
# 正則匹配(~ 區(qū)分大小寫,~* 不區(qū)分)
location ~ \.(jpg|png|gif)$ {
expires 30d; # 緩存控制
add_header Cache-Control "public, immutable";
}
# 前綴匹配(^~)
location ^~ /static/ {
# 匹配 /static/ 開頭的URI
alias /var/www/static/;
}
# API代理
location /api/ {
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;
# 超時(shí)設(shè)置
proxy_connect_timeout 30s;
proxy_read_timeout 30s;
proxy_send_timeout 30s;
}
# PHP處理
location ~ \.php$ {
fastcgi_pass unix:/var/run/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}三、高級配置示例
1. 負(fù)載均衡
upstream app_cluster {
least_conn; # 最少連接數(shù)
server app1.example.com:8080 max_fails=3 fail_timeout=30s;
server app2.example.com:8080;
server app3.example.com:8080 down; # 臨時(shí)下線
keepalive 32; # 連接池
}2. 緩存代理
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m
inactive=60m max_size=1g;
location / {
proxy_cache my_cache;
proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_use_stale error timeout updating;
}3. 限流
# 限制連接數(shù)
limit_conn_zone $binary_remote_addr zone=perip:10m;
# 限制請求速率
limit_req_zone $binary_remote_addr zone=perip:10m rate=10r/s;
location /api/ {
limit_conn perip 10; # 每個(gè)IP最多10個(gè)連接
limit_req zone=perip burst=20 nodelay; # 令牌桶算法
}4. 反向代理WebSocket
location /ws/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}四、配置最佳實(shí)踐
- 安全配置:
# 隱藏Nginx版本號
server_tokens off;
# 限制請求方法
if ($request_method !~ ^(GET|POST|HEAD)$) {
return 405;
}
# 防止目錄遍歷
autoindex off;
# 禁用不需要的HTTP方法
location / {
limit_except GET POST { deny all; }
}- 性能優(yōu)化:
# 文件緩存 open_file_cache max=1000 inactive=20s; open_file_cache_valid 30s; open_file_cache_min_uses 2; # 緩沖優(yōu)化 proxy_buffers 8 16k; proxy_buffer_size 32k; client_body_buffer_size 128k; # TCP優(yōu)化 sendfile_max_chunk 512k;
- 日志管理:
# 按天分割日志(在crontab中配置)
access_log /var/log/nginx/access-$(date +%Y%m%d).log;
# 排除靜態(tài)文件日志
location ~* \.(jpg|css|js)$ {
access_log off;
log_not_found off;
}五、調(diào)試和測試
# 檢查配置語法 nginx -t # 測試配置并顯示解析結(jié)果 nginx -T # 重新加載配置(不中斷服務(wù)) nginx -s reload # 調(diào)試特定問題 error_log /var/log/nginx/error.log debug;
六、常用變量
$remote_addr # 客戶端IP $http_host # 請求主機(jī)頭 $request_uri # 完整請求URI $args # 查詢參數(shù) $scheme # 協(xié)議(http/https) $server_name # 服務(wù)器名 $content_length # 請求體長度 $http_user_agent # 用戶代理 $status # 響應(yīng)狀態(tài)碼
七、配置組織建議
/etc/nginx/
├── nginx.conf # 主配置文件
├── conf.d/ # 通用配置片段
│ ├── gzip.conf
│ ├── security.conf
│ └── proxy.conf
├── sites-available/ # 可用站點(diǎn)配置
│ └── example.com.conf
├── sites-enabled/ # 啟用的站點(diǎn)(符號鏈接)
│ └── example.com.conf -> ../sites-available/example.com.conf
└── snippets/ # 可復(fù)用配置塊
└── ssl-params.conf到此這篇關(guān)于Nginx 配置示例及核心模塊詳解的文章就介紹到這了,更多相關(guān)nginx配置核心模塊內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Nginx實(shí)現(xiàn)負(fù)載均衡的配置步驟
Nginx是一個(gè)高性能的HTTP和反向代理服務(wù)器,它以其穩(wěn)定性、豐富的功能集、低系統(tǒng)資源消耗和簡單的配置而廣受歡迎,在大型網(wǎng)站和分布式系統(tǒng)中,Nginx常被用作負(fù)載均衡器,本文給大家介紹了Nginx負(fù)載均衡的配置步驟,需要的朋友可以參考下2024-06-06
Nginx多服務(wù)靜態(tài)資源路徑?jīng)_突問題及解決方案
在使用Nginx反向代理多個(gè)Flask應(yīng)用時(shí),不同服務(wù)的靜態(tài)資源路徑?jīng)_突導(dǎo)致加載錯(cuò)誤,接下來通過本文給大家介紹Nginx多服務(wù)靜態(tài)資源路徑?jīng)_突解決方案,感興趣的朋友跟隨小編一起看看吧2026-01-01
Nginx服務(wù)器的location指令匹配規(guī)則詳解
這篇文章主要介紹了Nginx服務(wù)器的location指令匹配規(guī)則,文中介紹了一種動靜態(tài)地址分離的方法示例,需要的朋友可以參考下2015-12-12
Nginx反向代理和內(nèi)容替換模塊實(shí)現(xiàn)網(wǎng)頁內(nèi)容動態(tài)替換功能
Nginx是一款輕量級高性能服務(wù)器軟件,雖然輕量,但功能非常強(qiáng)大,可用于提供WEB服務(wù)、反向代理、負(fù)載均衡、緩存服務(wù)、甚至可以通過添加一些模塊搭建rtmp流媒體服務(wù),最近碰到一個(gè)客戶需求,需要用到nginx反向代理替換網(wǎng)頁內(nèi)容,貼出來跟大家交流,如有不足之處請指出2024-10-10
nginx proxy_pass反向代理配置中url后加不加/的區(qū)別介紹
這篇文章主要給大家介紹了關(guān)于nginx proxy_pass反向代理配置中url后加不加/的區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-11-11
nginx 負(fù)載均衡配置及如何解決重復(fù)登錄問題
文章詳解Nginx源碼安裝與Docker部署,介紹四層/七層代理區(qū)別及負(fù)載均衡策略,通過ip_hash解決重復(fù)登錄問題,對nginx 負(fù)載均衡配置及如何解決重復(fù)登錄問題感興趣的朋友一起看看吧2025-07-07

