Nginx配置文件完全指南(非常詳細(xì)!)
前言
Nginx 的強(qiáng)大之處已無(wú)需多言,正由于它過(guò)于強(qiáng)大,配置文件里一個(gè)參數(shù)的不同就會(huì)有完全不同的行為,容易讓人摸不著頭腦,今天我們就來(lái)完整分析它的配置文件里面到底有什么內(nèi)容~
配置文件的基礎(chǔ)結(jié)構(gòu)
主配置文件位置
Nginx的主配置文件通常位于:
Linux系統(tǒng):
/etc/nginx/nginx.confmacOS(通過(guò)Homebrew安裝):
/usr/local/etc/nginx/nginx.confWindows系統(tǒng):
<安裝目錄>/conf/nginx.conf
配置文件的層級(jí)結(jié)構(gòu)
Nginx配置文件采用塊狀結(jié)構(gòu),主要分為以下幾個(gè)層級(jí):
# 全局塊
user nginx;
worker_processes auto;
# events 塊
events {
worker_connections 1024;
}
# http 塊
http {
# http 全局塊
include mime.types;
default_type application/octet-stream;
# server 塊
server {
# server 全局塊
listen 80;
server_name example.com;
# location 塊
location / {
root /var/www/html;
index index.html;
}
}
}全局塊配置詳解
全局塊是配置文件的最外層,影響 Nginx 服務(wù)器整體運(yùn)行的配置指令。
核心配置項(xiàng)
# 運(yùn)行 Nginx 的用戶和用戶組 user nginx nginx; # 工作進(jìn)程數(shù)(通常設(shè)置為 CPU 核心數(shù)) worker_processes auto; # 錯(cuò)誤日志路徑和級(jí)別 error_log /var/log/nginx/error.log warn; # 進(jìn)程 PID 文件位置 pid /var/run/nginx.pid; # 最大打開文件數(shù) worker_rlimit_nofile 65535;
關(guān)鍵參數(shù)說(shuō)明:
worker_processes:建議設(shè)置為auto或 CPU 核心數(shù),可通過(guò)grep processor /proc/cpuinfo | wc -l查看error_log級(jí)別從低到高:debug→info→notice→warn→error→crit
Events 塊配置
Events 塊主要影響 Nginx 服務(wù)器與用戶的網(wǎng)絡(luò)連接。
events {
# 單個(gè)工作進(jìn)程的最大連接數(shù)
worker_connections 10240;
# 使用 epoll 事件驅(qū)動(dòng)模型(Linux 推薦)
use epoll;
# 盡可能多地接受連接
multi_accept on;
}性能優(yōu)化建議:
worker_connections:理論最大并發(fā)連接數(shù) =worker_processes × worker_connectionsLinux 系統(tǒng)推薦使用
epoll,BSD 系統(tǒng)使用kqueue
HTTP 塊核心配置
HTTP 塊是配置的核心部分,包含了大部分 Web 服務(wù)相關(guān)的設(shè)置。
基礎(chǔ)配置
http {
# 引入 MIME 類型定義
include mime.types;
default_type application/octet-stream;
# 字符集
charset utf-8;
# 日志格式定義
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
# 訪問(wèn)日志
access_log /var/log/nginx/access.log main;
# 高效文件傳輸
sendfile on;
tcp_nopush on;
tcp_nodelay on;
# 連接超時(shí)時(shí)間
keepalive_timeout 65;
# 客戶端請(qǐng)求體大小限制
client_max_body_size 20m;
# Gzip 壓縮
gzip on;
gzip_vary on;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml text/javascript
application/json application/javascript application/xml+rss;
}性能優(yōu)化配置
http {
# 隱藏 Nginx 版本號(hào)(安全)
server_tokens off;
# 文件緩存
open_file_cache max=10000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
# 客戶端緩沖區(qū)大小
client_body_buffer_size 128k;
client_header_buffer_size 1k;
large_client_header_buffers 4 16k;
# FastCGI 緩存(用于 PHP 等)
fastcgi_cache_path /var/cache/nginx levels=1:2
keys_zone=my_cache:10m max_size=1g
inactive=60m use_temp_path=off;
}Server 塊配置詳解
Server 塊定義了一個(gè)虛擬主機(jī),一個(gè) HTTP 塊可以包含多個(gè) Server 塊。
基礎(chǔ)虛擬主機(jī)配置
server {
# 監(jiān)聽端口
listen 80;
listen [::]:80; # IPv6
# 服務(wù)器域名
server_name example.com www.example.com;
# 網(wǎng)站根目錄
root /var/www/example.com;
# 默認(rèn)首頁(yè)
index index.html index.htm index.php;
# 訪問(wèn)日志(可覆蓋 http 塊設(shè)置)
access_log /var/log/nginx/example.access.log;
error_log /var/log/nginx/example.error.log;
}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 配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
# SSL 會(huì)話緩存
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# HSTS(強(qiáng)制 HTTPS)
add_header Strict-Transport-Security "max-age=31536000" always;
}
# HTTP 自動(dòng)跳轉(zhuǎn) HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}Location 塊配置詳解
Location 塊是 Nginx 配置中最靈活的部分,用于匹配不同的 URI 請(qǐng)求。
Location 匹配規(guī)則
# 精確匹配(優(yōu)先級(jí)最高)
location = /exact {
# 只匹配 /exact
}
# 正則匹配(區(qū)分大小寫)
location ~ \.php$ {
# 匹配以.php結(jié)尾的請(qǐng)求
}
# 正則匹配(不區(qū)分大小寫)
location ~* \.(jpg|jpeg|png|gif)$ {
# 匹配圖片文件
}
# 前綴匹配(優(yōu)先級(jí)高于正則)
location ^~ /static/ {
# 匹配以/static/開頭的請(qǐng)求
}
# 普通前綴匹配
location /api/ {
# 匹配以/api/開頭的請(qǐng)求
}
# 通用匹配(最低優(yōu)先級(jí))
location / {
# 匹配所有請(qǐng)求
}匹配優(yōu)先級(jí)(從高到低):
=精確匹配^~前綴匹配~和~*正則匹配(按配置順序)普通前綴匹配(最長(zhǎng)匹配原則)
常見 Location 配置示例
靜態(tài)文件服務(wù)
location / {
root /var/www/html;
index index.html;
try_files $uri $uri/ =404;
}
# 靜態(tài)資源緩存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}反向代理配置
location /api/ {
proxy_pass http://backend_server;
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_send_timeout 60s;
proxy_read_timeout 60s;
}PHP-FPM 配置
location ~ \.php$ {
root /var/www/html;
fastcgi_pass unix:/var/run/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}負(fù)載均衡配置
Upstream 配置
# 定義后端服務(wù)器組
upstream backend {
# 負(fù)載均衡策略:輪詢(默認(rèn))
server 192.168.1.10:8080 weight=3;
server 192.168.1.11:8080 weight=2;
server 192.168.1.12:8080 backup; # 備份服務(wù)器
# 健康檢查
server 192.168.1.13:8080 max_fails=3 fail_timeout=30s;
# 保持連接
keepalive 32;
}
server {
location / {
proxy_pass http://backend;
}
}負(fù)載均衡策略
# IP Hash(同一客戶端固定訪問(wèn)同一服務(wù)器)
upstream backend {
ip_hash;
server backend1.example.com;
server backend2.example.com;
}
# 最少連接
upstream backend {
least_conn;
server backend1.example.com;
server backend2.example.com;
}
# URL Hash
upstream backend {
hash $request_uri consistent;
server backend1.example.com;
server backend2.example.com;
}安全配置最佳實(shí)踐
防止常見攻擊
# 限制請(qǐng)求方法
location / {
limit_except GET POST {
deny all;
}
}
# 防止 SQL 注入和 XSS(基礎(chǔ)防護(hù))
if ($request_uri ~* "(union|select|insert|delete|update|drop)") {
return 403;
}
# 防止目錄遍歷
location ~ /\. {
deny all;
}
# 限制文件上傳大小
client_max_body_size 10m;訪問(wèn)控制
# IP 白名單
location /admin/ {
allow 192.168.1.0/24;
allow 10.0.0.1;
deny all;
}
# HTTP 基本認(rèn)證
location /secure/ {
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/.htpasswd;
}限流配置
# 定義限流區(qū)域
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
location /api/ {
# 限制請(qǐng)求頻率(每秒 1 個(gè)請(qǐng)求,突發(fā)最多 5 個(gè))
limit_req zone=one burst=5 nodelay;
# 限制并發(fā)連接數(shù)
limit_conn addr 10;
}
}實(shí)戰(zhàn)配置案例
完整的 WordPress 網(wǎng)站配置
server {
listen 80;
server_name myblog.com www.myblog.com;
root /var/www/wordpress;
index index.php index.html;
access_log /var/log/nginx/myblog.access.log;
error_log /var/log/nginx/myblog.error.log;
# WordPress固定鏈接
location / {
try_files $uri $uri/ /index.php?$args;
}
# 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;
}
# 靜態(tài)資源緩存
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
# 禁止訪問(wèn)敏感文件
location ~ /\.(ht|git) {
deny all;
}
# 禁止訪問(wèn) wp-config.php
location = /wp-config.php {
deny all;
}
}前后端分離的單頁(yè)應(yīng)用(SPA)配置
server {
listen 80;
server_name app.example.com;
root /var/www/vue-app/dist;
# SPA路由支持
location / {
try_files $uri $uri/ /index.html;
}
# API反向代理
location /api/ {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
# WebSocket支持
location /ws/ {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}配置文件管理與調(diào)試
配置文件模塊化
建議將配置拆分為多個(gè)文件:
# 主配置文件 nginx.conf
http {
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}推薦的目錄結(jié)構(gòu):
/etc/nginx/
├── nginx.conf # 主配置文件
├── mime.types # MIME 類型
├── conf.d/ # 通用配置
│ ├── security.conf # 安全配置
│ ├── ssl.conf # SSL 通用配置
│ ├── gzip.conf # 壓縮配置
│ └── proxy.conf # 代理通用配置
├── sites-available/ # 站點(diǎn)配置(所有)
│ ├── default
│ ├── example.com.conf
│ └── api.example.com.conf
├── sites-enabled/ # 啟用的站點(diǎn)(軟鏈接)
│ └── example.com.conf -> ../sites-available/example.com.conf
├── snippets/ # 可復(fù)用的配置片段
│ ├── ssl-params.conf
│ ├── proxy-params.conf
│ └── fastcgi-php.conf
└── ssl/ # SSL 證書
├── example.com.crt
├── example.com.key
└── dhparam.pem配置驗(yàn)證與重載
# 檢查配置文件語(yǔ)法 nginx -t # 重新加載配置(不中斷服務(wù)) nginx -s reload # 停止Nginx nginx -s stop # 優(yōu)雅停止(等待當(dāng)前請(qǐng)求完成) nginx -s quit
常見問(wèn)題排查
# 查看錯(cuò)誤日志 tail -f /var/log/nginx/error.log # 查看訪問(wèn)日志 tail -f /var/log/nginx/access.log # 檢查Nginx進(jìn)程 ps aux | grep nginx # 檢查端口占用 netstat -tulpn | grep :80
寫在最后
配置關(guān)鍵要點(diǎn):
結(jié)構(gòu)清晰:使用模塊化配置,便于管理和維護(hù)
安全第一:隱藏版本號(hào)、配置SSL、設(shè)置訪問(wèn)控制
性能優(yōu)化:合理配置 worker 進(jìn)程、啟用 Gzip、設(shè)置緩存
日志管理:定期清理日志,使用日志切割工具
持續(xù)學(xué)習(xí):Nginx 功能強(qiáng)大,需要根據(jù)實(shí)際場(chǎng)景不斷優(yōu)化
學(xué)習(xí)建議:
從基礎(chǔ)配置開始,逐步深入高級(jí)功能
在測(cè)試環(huán)境充分驗(yàn)證后再應(yīng)用到生產(chǎn)環(huán)境
關(guān)注 Nginx 官方文檔和社區(qū)最佳實(shí)踐
定期審查和優(yōu)化配置文件
在 Nginx 配置文件中,以 $ 開頭的變量是 Nginx 內(nèi)置的預(yù)定義變量,它們?cè)谡?qǐng)求處理過(guò)程中會(huì)被自動(dòng)賦值。理解這些變量對(duì)于編寫靈活的配置至關(guān)重要。不要被它們嚇倒,雖然 Nginx 沒有內(nèi)置命令列出所有變量,但可以參考官方文檔,見相關(guān)資源部分。實(shí)踐是最好的學(xué)習(xí)方式,動(dòng)手試試吧!
到此這篇關(guān)于Nginx配置文件完全指南的文章就介紹到這了,更多相關(guān)Nginx配置文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
結(jié)合 Nginx 將 DoNetCore 部署到 阿里云的安裝配置方法
這篇文章主要介紹了結(jié)合 Nginx 將 DoNetCore 部署到 阿里云的方法 ,需要的朋友可以參考下2018-10-10
nginx部署前端項(xiàng)目后刷新瀏覽器報(bào)錯(cuò)404問(wèn)題解決
現(xiàn)在前端頁(yè)面部署正常訪問(wèn),但是刷新的時(shí)候出現(xiàn)了404,所以下面給整理下,這篇文章主要給大家介紹了關(guān)于nginx部署前端項(xiàng)目后刷新瀏覽器報(bào)錯(cuò)404問(wèn)題的解決辦法,需要的朋友可以參考下2023-11-11
Nginx通過(guò)代理服務(wù)器訪問(wèn)目標(biāo)接口的實(shí)現(xiàn)
本文主要介紹了Nginx通過(guò)代理服務(wù)器訪問(wèn)目標(biāo)接口的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-08-08
Nginx 配置跨域的實(shí)現(xiàn)及常見問(wèn)題解決
本文主要介紹了Nginx 配置跨域的實(shí)現(xiàn)及常見問(wèn)題解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2025-06-06
Nginx基礎(chǔ)location語(yǔ)法及功能配置實(shí)例
這篇文章主要為大家介紹了Nginx基礎(chǔ)location語(yǔ)法及功能以及配置實(shí)例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-03-03
詳解nginx同一端口監(jiān)聽多個(gè)域名和同時(shí)監(jiān)聽http與https
這篇文章主要介紹了詳解nginx同一端口監(jiān)聽多個(gè)域名和同時(shí)監(jiān)聽http與https的相關(guān)資料,需要的朋友可以參考下2017-05-05

