系列文章索引:
- 第一篇:《Nginx入門與安裝詳解:從零開始搭建高性能Web服務器》
- 第二篇:《Nginx基礎配置詳解:nginx.conf核心配置與虛擬主機實戰》
- 第三篇:《Nginx代理配置詳解:正向代理與反向代理完全指南》
- 第四篇:《Nginx性能優化與安全配置:打造高性能Web服務器》
- 第五篇:《Nginx負載均衡配置詳解:多種負載均衡策略實戰》
- 第六篇:《Nginx高可用方案實戰:Keepalived+雙機熱備部署》
前言
在高并發、大流量的互聯網時代,Web服務器的性能和安全性直接關系到用戶體驗和業務穩定性。Nginx作為高性能Web服務器的代表,通過合理的優化配置可以發揮出極致性能,同時通過完善的安全配置可以有效抵御各種網絡攻擊。
本文將深入探討Nginx的性能優化和安全配置,從內核參數調整到應用層優化,從基礎安全防護到高級安全策略,幫助你打造一個既高性能又安全的Web服務器環境。
一、Nginx性能優化詳解
1.1 工作進程優化
工作進程數配置
# =============================================
# 工作進程優化配置
# =============================================# 工作進程數設置
# auto:自動設置為CPU核心數
# 生產環境建議設置為CPU核心數或核心數x2
worker_processes auto;# 工作進程CPU親和性綁定
# auto:自動綁定CPU核心,提高緩存命中率
# 手動綁定示例:worker_cpu_affinity 0001 0010 0100 1000;
worker_cpu_affinity auto;# 工作進程優先級設置
# 范圍:-20到19,數值越低優先級越高
# worker_priority -5;# 工作進程的最大文件描述符數量
# 建議設置為65535或更高
worker_rlimit_nofile 65535;# 工作進程信號處理
worker_shutdown_timeout 10s;
配置說明:
worker_processes auto
:自動根據CPU核心數設置工作進程數worker_cpu_affinity auto
:自動將工作進程綁定到特定CPU核心worker_rlimit_nofile
:限制單個工作進程能打開的最大文件數
工作進程優化建議
CPU核心數判斷:
# 查看CPU核心數
nproc
# 或
cat /proc/cpuinfo | grep processor | wc -l# 查看CPU信息
lscpu
優化策略:
- CPU密集型應用:
worker_processes
設置為CPU核心數 - I/O密集型應用:
worker_processes
設置為CPU核心數×2 - 混合型應用:
worker_processes
設置為CPU核心數×1.5
1.2 事件模型優化
事件模型配置
# =============================================
# 事件模型優化配置
# =============================================events {# 單個工作進程允許的最大連接數# 理論最大值 = worker_processes * worker_connections# 建議設置為65535worker_connections 65535;# 事件驅動模型選擇# Linux推薦使用epoll# FreeBSD推薦使用kqueue# Solaris推薦使用eventportuse epoll;# 是否允許同時接受多個連接# 提高連接處理效率,建議開啟multi_accept on;# 工作進程是否可以同時接受多個連接# 提高并發處理能力accept_mutex on;# 接受連接的超時時間accept_mutex_delay 500ms;# 是否使用異步文件I/O# 需要編譯時啟用 --with-file-aioaio on;# 是否使用sendfile系統調用# 高效傳輸文件,建議開啟sendfile on;# 是否使用TCP_NOPUSH套接字選項# 在sendfile開啟時有效,減少網絡包數量tcp_nopush on;# 是否使用TCP_NODELAY套接字選項# 禁用Nagle算法,減少網絡延遲tcp_nodelay on;# 連接超時時間# 單位:秒keepalive_timeout 65;# 單個連接的最大請求數keepalive_requests 1000;# 隱藏Nginx版本信息server_tokens off;
}
事件模型說明:
epoll
:Linux下最高效的事件模型,支持大量連接kqueue
:FreeBSD下的事件模型,性能優秀eventport
:Solaris下的事件模型select
:通用事件模型,性能較差
事件模型選擇建議
# 檢查系統支持的事件模型
nginx -V 2>&1 | grep -o -- '--with-.*_module'# 查看系統信息
uname -a
cat /etc/os-release
不同系統的推薦配置:
- Linux系統:
use epoll;
- FreeBSD系統:
use kqueue;
- Solaris系統:
use eventport;
- 通用配置:不設置,讓Nginx自動選擇
1.3 連接優化
連接參數配置
# =============================================
# 連接優化配置
# =============================================http {# =============================================# 基本連接優化# =============================================# 客戶端請求頭緩沖區大小client_header_buffer_size 4k;# 大客戶端請求頭緩沖區數量和大小large_client_header_buffers 8 4k;# 客戶端請求體緩沖區大小client_body_buffer_size 128k;# 客戶端請求體最大大小client_max_body_size 50m;# 客戶端連接超時時間client_header_timeout 30s;client_body_timeout 30s;# 發送響應超時時間send_timeout 30s;# 保持連接超時時間keepalive_timeout 65s;# 單個長連接的最大請求數keepalive_requests 1000;# 重置超時連接reset_timedout_connection on;# =============================================# 上游服務器連接優化# =============================================# 上游服務器連接超時proxy_connect_timeout 60s;proxy_send_timeout 60s;proxy_read_timeout 60s;# FastCGI連接超時fastcgi_connect_timeout 60s;fastcgi_send_timeout 60s;fastcgi_read_timeout 60s;# uWSGI連接超時uwsgi_connect_timeout 60s;uwsgi_send_timeout 60s;uwsgi_read_timeout 60s;# SCGI連接超時scgi_connect_timeout 60s;scgi_send_timeout 60s;scgi_read_timeout 60s;# =============================================# 內存優化# =============================================# 輸出緩沖區大小output_buffers 2 32k;# 推遲發送響應頭postpone_output 1460;# 限制請求處理速率limit_rate 1024k;limit_rate_after 500k;
}
連接優化說明:
client_header_buffer_size
:客戶端請求頭緩沖區大小client_body_buffer_size
:客戶端請求體緩沖區大小client_max_body_size
:客戶端請求體最大大小keepalive_timeout
:長連接超時時間reset_timedout_connection
:重置超時連接
1.4 緩存優化
文件緩存配置
# =============================================
# 文件緩存優化配置
# =============================================http {# =============================================# 文件緩存配置# =============================================# 開啟文件緩存open_file_cache max=100000 inactive=20s;# 文件緩存有效時間open_file_cache_valid 30s;# 文件緩存最小使用次數open_file_cache_min_uses 2;# 是否緩存文件錯誤信息open_file_cache_errors on;# =============================================# 代理緩存配置# =============================================# 代理緩存路徑配置proxy_cache_path /usr/local/nginx/proxy_cache levels=1:2 keys_zone=proxy_cache:10m inactive=60m max_size=10g use_temp_path=off;# 代理緩存臨時文件路徑proxy_temp_path /usr/local/nginx/proxy_temp;# 代理緩存級別proxy_cache_levels 1:2;# 代理緩存鍵proxy_cache_key $scheme$request_method$host$request_uri;# 代理緩存有效期proxy_cache_valid 200 302 10m;proxy_cache_valid 301 1h;proxy_cache_valid 404 1m;proxy_cache_valid 500 502 503 504 0s;# 代理緩存使用策略proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;# 代理緩存鎖定proxy_cache_lock on;proxy_cache_lock_timeout 5s;# 代理緩存繞過proxy_cache_bypass $cookie_nocache $arg_nocache $arg_comment;proxy_no_cache $cookie_nocache $arg_nocache $arg_comment;# =============================================# FastCGI緩存配置# =============================================# FastCGI緩存路徑fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2 keys_zone=fastcgi_cache:10m inactive=60m max_size=5g use_temp_path=off;# FastCGI緩存鍵fastcgi_cache_key $scheme$request_method$host$request_uri;# FastCGI緩存有效期fastcgi_cache_valid 200 302 10m;fastcgi_cache_valid 301 1h;fastcgi_cache_valid 404 1m;# FastCGI緩存使用策略fastcgi_cache_use_stale error timeout invalid_header http_500 http_503;# FastCGI緩存繞過fastcgi_cache_bypass $cookie_nocache $arg_nocache;fastcgi_no_cache $cookie_nocache $arg_nocache;
}
緩存優化說明:
open_file_cache
:文件描述符緩存,提高文件訪問性能proxy_cache_path
:代理緩存路徑配置fastcgi_cache_path
:FastCGI緩存路徑配置proxy_cache_valid
:代理緩存有效期配置fastcgi_cache_valid
:FastCGI緩存有效期配置
緩存策略配置
# =============================================
# 緩存策略配置
# =============================================http {# =============================================# 緩存條件變量# =============================================# 定義緩存條件變量map $request_method $no_cache_method {POST 1;PUT 1;DELETE 1;PATCH 1;default 0;}map $cookie_user_token $no_cache_auth {default 0;"~*" 1;}map $arg_nocache $no_cache_arg {default 0;"1" 1;"true" 1;}# =============================================# 靜態資源緩存# =============================================server {listen 80;server_name cache.example.com;# 靜態資源緩存配置location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2|ttf|eot|svg)$ {# 瀏覽器緩存expires 30d;add_header Cache-Control "public, no-transform";# 代理緩存proxy_cache proxy_cache;proxy_cache_valid 200 302 7d;proxy_cache_valid 404 1h;proxy_cache_key $scheme$request_method$host$request_uri;# 緩存狀態add_header X-Proxy-Cache $upstream_cache_status;# 關閉訪問日志access_log off;}# =============================================# 動態內容緩存# =============================================location / {proxy_pass http://backend;proxy_set_header Host $host;# 動態內容緩存proxy_cache proxy_cache;proxy_cache_valid 200 302 5m;proxy_cache_valid 404 1m;proxy_cache_key $scheme$request_method$host$request_uri;# 條件緩存proxy_no_cache $no_cache_method $no_cache_auth $no_cache_arg;proxy_cache_bypass $no_cache_method $no_cache_auth $no_cache_arg;# 緩存狀態add_header X-Proxy-Cache $upstream_cache_status;}}
}
1.5 壓縮優化
Gzip壓縮配置
# =============================================
# Gzip壓縮優化配置
# =============================================http {# =============================================# 基礎Gzip配置# =============================================# 是否開啟Gzip壓縮gzip on;# 啟用Gzip壓縮的最小文件大小gzip_min_length 1k;# Gzip壓縮緩沖區大小gzip_buffers 4 16k;# Gzip壓縮版本gzip_http_version 1.1;# Gzip壓縮級別(1-9)# 1: 壓縮速度最快,壓縮率最低# 9: 壓縮速度最慢,壓縮率最高# 建議設置為6gzip_comp_level 6;# 需要壓縮的MIME類型gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript application/x-javascript application/vnd.ms-fontobject application/x-font-ttf font/opentype image/svg+xml image/x-icon;# 是否在響應頭中添加Vary: Accept-Encodinggzip_vary on;# 禁用IE6的Gzip壓縮gzip_disable "MSIE [1-6]\.";# =============================================# 高級Gzip配置# =============================================# 啟用Gzip靜態壓縮gzip_static on;# Gzip壓縮比例gzip_proxied any;# Gzip壓縮的最小HTTP版本gzip_http_version 1.1;# =============================================# Brotli壓縮配置(需要額外模塊)# =============================================# 啟用Brotli壓縮# brotli on;# Brotli壓縮級別(0-11)# brotli_comp_level 6;# Brotli壓縮的最小文件大小# brotli_min_length 1k;# Brotli壓縮類型# brotli_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
}
壓縮優化說明:
gzip on
:開啟Gzip壓縮gzip_comp_level
:壓縮級別,建議設置為6gzip_types
:需要壓縮的MIME類型gzip_min_length
:壓縮的最小文件大小gzip_vary on
:添加Vary頭信息
1.6 系統級優化
內核參數優化
# =============================================
# 內核參數優化配置
# 添加到 /etc/sysctl.conf
# =============================================# 文件描述符限制
fs.file-max = 1000000# 網絡連接優化
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 1200
net.ipv4.ip_local_port_range = 10000 65000# 內存優化
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216# 網絡安全優化
net.ipv4.tcp_syncookies = 1
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
應用內核參數:
# 應用內核參數
sysctl -p# 驗證參數是否生效
sysctl -a | grep file-max
sysctl -a | grep somaxconn
系統限制優化
# =============================================
# 系統限制優化配置
# 添加到 /etc/security/limits.conf
# =============================================# 文件描述符限制
* soft nofile 65535
* hard nofile 65535
nginx soft nofile 65535
nginx hard nofile 65535# 進程數限制
* soft nproc 65535
* hard nproc 65535
nginx soft nproc 65535
nginx hard nproc 65535# 內存限制
* soft as unlimited
* hard as unlimited
nginx soft as unlimited
nginx hard as unlimited
Systemd服務優化
# =============================================
# Systemd服務優化配置
# 創建 /etc/systemd/system/nginx.service.d/limits.conf
# =============================================[Service]
LimitNOFILE=65535
LimitNPROC=65535
LimitAS=infinity
LimitMEMLOCK=infinity
重新加載Systemd配置:
# 重新加載Systemd配置
systemctl daemon-reload# 重啟Nginx服務
systemctl restart nginx# 驗證限制是否生效
cat /proc/$(pgrep nginx)/limits | grep "Max open files"
二、Nginx安全配置詳解
2.1 基礎安全配置
隱藏版本信息
# =============================================
# 基礎安全配置
# =============================================http {# 隱藏Nginx版本信息server_tokens off;# 隱藏PHP版本信息(如果使用PHP)fastcgi_hide_header X-Powered-By;# 隱藏服務器信息more_clear_headers Server;# =============================================# 安全頭配置# =============================================# 防止點擊劫持add_header X-Frame-Options "SAMEORIGIN" always;# 防止XSS攻擊add_header X-XSS-Protection "1; mode=block" always;# 防止MIME類型嗅探add_header X-Content-Type-Options "nosniff" always;# 內容安全策略add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self'; frame-src 'self';" always;# 引用策略add_header Referrer-Policy "strict-origin-when-cross-origin" always;# 權限策略add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=()" always;
}
安全頭說明:
X-Frame-Options
:防止點擊劫持攻擊X-XSS-Protection
:啟用XSS過濾器X-Content-Type-Options
:防止MIME類型嗅探Content-Security-Policy
:內容安全策略Referrer-Policy
:引用策略Permissions-Policy
:權限策略
敏感信息隱藏
# =============================================
# 敏感信息隱藏配置
# =============================================http {# 隱藏Nginx版本信息server_tokens off;# 隱藏PHP版本信息fastcgi_hide_header X-Powered-By;# 隱藏服務器信息proxy_hide_header X-Powered-By;proxy_hide_header X-Version;proxy_hide_header X-AspNet-Version;proxy_hide_header X-Drupal-Cache;proxy_hide_header X-Generator;# 隱藏錯誤信息中的服務器信息fastcgi_intercept_errors on;fastcgi_hide_header X-Powered-By;# 自定義錯誤頁面error_page 404 /404.html;error_page 500 502 503 504 /50x.html;# 禁止訪問Nginx狀態頁面location /nginx_status {stub_status on;access_log off;allow 127.0.0.1;allow 192.168.1.0/24;deny all;}
}
2.2 訪問控制
IP訪問控制
# =============================================
# IP訪問控制配置
# =============================================http {# =============================================# 全局訪問控制# =============================================# 允許的IP列表allow 127.0.0.1;allow 192.168.1.0/24;allow 10.0.0.0/8;# 拒絕所有其他IPdeny all;# =============================================# 站點訪問控制# =============================================server {listen 80;server_name secure.example.com;# 管理后臺訪問控制location /admin/ {# 只允許內網IP訪問allow 192.168.1.0/24;allow 10.0.0.0/8;deny all;# 基本認證auth_basic "Admin Area";auth_basic_user_file /usr/local/nginx/conf/htpasswd.admin;# 嘗試訪問文件try_files $uri $uri/ /admin/index.html;}# API訪問控制location /api/ {# 限制請求頻率limit_req zone=api_limit burst=20 nodelay;# 只允許特定IP訪問allow 192.168.1.0/24;allow 10.0.0.0/8;deny all;# 代理到后端proxy_pass http://backend;proxy_set_header Host $host;}# 靜態資源訪問控制location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {# 允許所有IP訪問靜態資源allow all;# 設置緩存expires 7d;add_header Cache-Control "public, no-transform";# 關閉訪問日志access_log off;}}
}
請求頻率限制
# =============================================
# 請求頻率限制配置
# =============================================http {# =============================================# 請求頻率限制定義# =============================================# 定義API請求限制區域limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;# 定義登錄請求限制區域limit_req_zone $binary_remote_addr zone=login_limit:10m rate=5r/m;# 定義下載請求限制區域limit_req_zone $binary_remote_addr zone=download_limit:10m rate=2r/s;# 定義連接限制區域limit_conn_zone $binary_remote_addr zone=conn_limit:10m;# =============================================# 請求頻率限制應用# =============================================server {listen 80;server_name rate-limit.example.com;# API請求限制location /api/ {# 應用請求限制limit_req zone=api_limit burst=20 nodelay;# 應用連接限制limit_conn conn_limit 100;# 代理到后端proxy_pass http://backend;proxy_set_header Host $host;# 添加限制信息到響應頭add_header X-RateLimit-Limit 10;add_header X-RateLimit-Remaining 10;add_header X-RateLimit-Reset 60;}# 登錄請求限制location /login {# 應用登錄請求限制limit_req zone=login_limit burst=3 nodelay;# 處理登錄請求proxy_pass http://backend/login;proxy_set_header Host $host;}# 下載請求限制location /download/ {# 應用下載請求限制limit_req zone=download_limit burst=5 nodelay;# 應用連接限制limit_conn conn_limit 5;# 設置下載速度限制limit_rate 1024k;limit_rate_after 500k;# 處理下載請求proxy_pass http://backend/download;proxy_set_header Host $host;}# =============================================# 限制錯誤處理# =============================================# 請求過多錯誤頁面error_page 429 /429.html;location = /429.html {internal;root /usr/local/nginx/html;}# 連接過多錯誤頁面error_page 503 /503.html;location = /503.html {internal;root /usr/local/nginx/html;}}
}
請求頻率限制說明:
limit_req_zone
:定義請求限制區域limit_req
:應用請求限制limit_conn_zone
:定義連接限制區域limit_conn
:應用連接限制limit_rate
:限制下載速度
2.3 SSL/TLS安全配置
SSL安全配置
# =============================================
# SSL/TLS安全配置
# =============================================server {# 監聽443端口(HTTPS)listen 443 ssl http2;listen [::]:443 ssl http2;# 服務器名稱server_name secure.example.com;# SSL證書配置ssl_certificate /usr/local/nginx/conf/ssl/secure.example.com.crt;ssl_certificate_key /usr/local/nginx/conf/ssl/secure.example.com.key;# SSL證書鏈ssl_trusted_certificate /usr/local/nginx/conf/ssl/chain.pem;# =============================================# SSL協議配置# =============================================# 啟用的SSL協議版本ssl_protocols TLSv1.2 TLSv1.3;# 禁用不安全的SSL協議# ssl_protocols TLSv1.2 TLSv1.3;# =============================================# SSL加密套件配置# =============================================# SSL加密套件ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384;# 優先使用服務器加密套件ssl_prefer_server_ciphers on;# 禁用不安全的加密套件ssl_ciphers "!aNULL:!MD5:!DSS:!3DES:!RC4:!SEED:!IDEA:!PSK:!SRP:!EXP";# =============================================# SSL會話配置# =============================================# SSL會話緩存ssl_session_cache shared:SSL:10m;ssl_session_timeout 10m;ssl_session_tickets on;# SSL會話票據密鑰ssl_session_ticket_key /usr/local/nginx/conf/ssl/session_ticket.key;# =============================================# SSL高級配置# =============================================# OCSP裝訂ssl_stapling on;ssl_stapling_verify on;ssl_stapling_file /usr/local/nginx/conf/ssl/stapling.ocsp;# OCSP響應超時resolver 8.8.8.8 8.8.4.4 valid=300s;resolver_timeout 5s;# SSL雙向認證(可選)# ssl_client_certificate /usr/local/nginx/conf/ssl/client_ca.crt;# ssl_verify_client on;# ssl_verify_depth 2;# =============================================# HSTS配置# =============================================# 嚴格傳輸安全add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;# =============================================# 安全頭配置# =============================================# 防止點擊劫持add_header X-Frame-Options "SAMEORIGIN" always;# 防止XSS攻擊add_header X-XSS-Protection "1; mode=block" always;# 防止MIME類型嗅探add_header X-Content-Type-Options "nosniff" always;# 內容安全策略add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; connect-src 'self' https:; frame-src 'self';" always;# =============================================# SSL相關代理配置# =============================================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;proxy_set_header X-Forwarded-SSL $ssl_protocol;proxy_set_header X-Forwarded-SSL-Cipher $ssl_cipher;proxy_set_header X-Forwarded-SSL-Session $ssl_session_id;# 設置HTTPS參數proxy_set_header HTTPS on;proxy_set_header HTTP_SCHEME https;}
}# =============================================
# HTTP重定向到HTTPS
# =============================================server {listen 80;listen [::]:80;server_name secure.example.com;# 重定向到HTTPSreturn 301 https://$server_name$request_uri;
}
SSL安全配置說明:
ssl_protocols
:啟用安全的SSL協議版本ssl_ciphers
:配置安全的加密套件ssl_prefer_server_ciphers
:優先使用服務器加密套件ssl_stapling
:啟用OCSP裝訂Strict-Transport-Security
:啟用HSTS
2.4 防攻擊配置
防SQL注入
# =============================================
# 防SQL注入配置
# =============================================http {# =============================================# SQL注入檢測規則# =============================================# 檢測SQL注入關鍵字if ($args ~* "union.*select.*\(") {return 403;}if ($args ~* "union.*all.*select") {return 403;}if ($args ~* "concat.*\(") {return 403;}if ($args ~* "base64_") {return 403;}if ($args ~* "/etc/passwd") {return 403;}if ($args ~* "proc/self/environ") {return 403;}if ($args ~* "select.*from") {return 403;}if ($args ~* "insert.*into") {return 403;}if ($args ~* "delete.*from") {return 403;}if ($args ~* "update.*set") {return 403;}if ($args ~* "drop.*table") {return 403;}if ($args ~* "alter.*table") {return 403;}if ($args ~* "create.*table") {return 403;}# =============================================# 文件包含攻擊檢測# =============================================if ($args ~* "local.*include") {return 403;}if ($args ~* "remote.*include") {return 403;}if ($args ~* "php://filter") {return 403;}if ($args ~* "data://") {return 403;}if ($args ~* "expect://") {return 403;}# =============================================# 命令注入檢測# =============================================if ($args ~* "cmd|sh|system|exec|passthru|shell_exec|proc_open|popen") {return 403;}if ($args ~* "\.\./") {return 403;}if ($args ~* "<script") {return 403;}if ($args ~* "javascript:") {return 403;}if ($args ~* "vbscript:") {return 403;}if ($args ~* "onload=") {return 403;}if ($args ~* "onerror=") {return 403;}
}
防XSS攻擊
# =============================================
# 防XSS攻擊配置
# =============================================http {# =============================================# XSS攻擊檢測規則# =============================================# 檢測XSS攻擊特征if ($args ~* "<script") {return 403;}if ($args ~* "javascript:") {return 403;}if ($args ~* "vbscript:") {return 403;}if ($args ~* "onload=") {return 403;}if ($args ~* "onerror=") {return 403;}if ($args ~* "onclick=") {return 403;}if ($args ~* "onfocus=") {return 403;}if ($args ~* "onblur=") {return 403;}if ($args ~* "onchange=") {return 403;}if ($args ~* "onsubmit=") {return 403;}if ($args ~* "onreset=") {return 403;}if ($args ~* "onselect=") {return 403;}if ($args ~* "onunload=") {return 403;}if ($args ~* "ondblclick=") {return 403;}if ($args ~* "onkeydown=") {return 403;}if ($args ~* "onkeypress=") {return 403;}if ($args ~* "onkeyup=") {return 403;}if ($args ~* "onmousedown=") {return 403;}if ($args ~* "onmouseup=") {return 403;}if ($args ~* "onmouseover=") {return 403;}if ($args ~* "onmouseout=") {return 403;}if ($args ~* "onmousemove=") {return 403;}# =============================================# XSS防護頭配置# =============================================# 防止XSS攻擊add_header X-XSS-Protection "1; mode=block" always;# 內容安全策略add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; connect-src 'self' https:; frame-src 'self'; object-src 'none';" always;# 防止MIME類型嗅探add_header X-Content-Type-Options "nosniff" always;
}
防CC攻擊
# =============================================
# 防CC攻擊配置
# =============================================http {# =============================================# CC攻擊防護定義# =============================================# 定義請求限制區域limit_req_zone $binary_remote_addr zone=cc_limit:10m rate=10r/s;limit_req_zone $binary_remote_addr zone=cc_strict:10m rate=5r/m;# 定義連接限制區域limit_conn_zone $binary_remote_addr zone=cc_conn:10m;# =============================================# CC攻擊防護應用# =============================================server {listen 80;server_name cc-protection.example.com;# 全局請求限制limit_req zone=cc_limit burst=20 nodelay;limit_conn cc_conn 100;# 敏感路徑嚴格限制location /admin/ {limit_req zone=cc_strict burst=3 nodelay;limit_conn cc_conn 5;# IP白名單allow 192.168.1.0/24;allow 10.0.0.0/8;deny all;# 基本認證auth_basic "Admin Area";auth_basic_user_file /usr/local/nginx/conf/htpasswd.admin;}# 登錄頁面嚴格限制location /login {limit_req zone=cc_strict burst=3 nodelay;limit_conn cc_conn 3;# 檢測異常登錄行為if ($http_user_agent ~* "bot|spider|crawler") {return 403;}# 代理到后端proxy_pass http://backend/login;proxy_set_header Host $host;}# API接口限制location /api/ {limit_req zone=cc_limit burst=10 nodelay;limit_conn cc_conn 50;# 檢測異常請求if ($request_method !~ ^(GET|POST|PUT|DELETE|OPTIONS)$) {return 405;}# 代理到后端proxy_pass http://backend;proxy_set_header Host $host;}# =============================================# User-Agent過濾# =============================================# 惡意User-Agent過濾if ($http_user_agent ~* "bot|spider|crawler|scraper") {return 403;}if ($http_user_agent ~* "curl|wget|python-requests") {return 403;}if ($http_user_agent ~* "nikto|nmap|sqlmap") {return 403;}# =============================================# 請求方法限制# =============================================# 限制請求方法if ($request_method !~ ^(GET|HEAD|POST)$ ) {return 405;}# =============================================# 錯誤處理# =============================================# 請求過多錯誤頁面error_page 429 /429.html;location = /429.html {internal;root /usr/local/nginx/html;}# 連接過多錯誤頁面error_page 503 /503.html;location = /503.html {internal;root /usr/local/nginx/html;}}
}
2.5 日志安全配置
安全日志配置
# =============================================
# 日志安全配置
# =============================================http {# =============================================# 日志格式定義# =============================================# 標準日志格式log_format main '$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for"';# 安全日志格式log_format security '$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for" ''rt=$request_time uct="$upstream_connect_time" ''uht="$upstream_header_time" urt="$upstream_response_time"';# JSON格式日志(便于ELK分析)log_format json escape=json '{''"timestamp": "$time_iso8601",''"remote_addr": "$remote_addr",''"remote_user": "$remote_user",''"request": "$request",''"status": $status,''"body_bytes_sent": $body_bytes_sent,''"http_referer": "$http_referer",''"http_user_agent": "$http_user_agent",''"http_x_forwarded_for": "$http_x_forwarded_for",''"request_time": $request_time,''"upstream_connect_time": "$upstream_connect_time",''"upstream_header_time": "$upstream_header_time",''"upstream_response_time": "$upstream_response_time"''}';# =============================================# 訪問日志配置# =============================================# 全局訪問日志access_log /var/log/nginx/access.log main;# 安全訪問日志access_log /var/log/nginx/security.log security;# JSON格式訪問日志access_log /var/log/nginx/access.json.log json;# =============================================# 錯誤日志配置# =============================================# 錯誤日志級別和路徑error_log /var/log/nginx/error.log warn;# 安全錯誤日志error_log /var/log/nginx/security_error.log crit;# =============================================# 站點日志配置# =============================================server {listen 80;server_name log-security.example.com;# 站點訪問日志access_log /var/log/nginx/log-security.example.com.access.log main;# 站點錯誤日志error_log /var/log/nginx/log-security.example.com.error.log warn;# =============================================# 敏感路徑日志配置# =============================================# 管理后臺詳細日志location /admin/ {access_log /var/log/nginx/admin.access.log security;# 記錄所有請求頭log_format admin '$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for" ''"$http_cookie" "$http_authorization"';access_log /var/log/nginx/admin.detailed.log admin;}# API接口詳細日志location /api/ {access_log /var/log/nginx/api.access.log security;# 記錄API詳細信息log_format api '$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for" ''rt=$request_time uct="$upstream_connect_time" ''uht="$upstream_header_time" urt="$upstream_response_time" ''req_body="$request_body"';access_log /var/log/nginx/api.detailed.log api;}# 靜態資源簡單日志location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {access_log off;}# =============================================# 錯誤頁面日志# =============================================# 4xx錯誤日志error_page 400 401 403 404 /4xx.html;location = /4xx.html {internal;root /usr/local/nginx/html;# 記錄4xx錯誤access_log /var/log/nginx/4xx_errors.log security;}# 5xx錯誤日志error_page 500 502 503 504 /5xx.html;location = /5xx.html {internal;root /usr/local/nginx/html;# 記錄5xx錯誤access_log /var/log/nginx/5xx_errors.log security;}}
}
日志輪轉配置
# =============================================
# 日志輪轉配置
# 創建 /etc/logrotate.d/nginx
# =============================================/var/log/nginx/*.log {dailymissingokrotate 52compressdelaycompressnotifemptycreate 644 nginx nginxpostrotateif [ -f /var/run/nginx.pid ]; thenkill -USR1 `cat /var/run/nginx.pid`fiendscript
}# =============================================
# 安全日志輪轉配置
# =============================================/var/log/nginx/security*.log {dailymissingokrotate 90compressdelaycompressnotifemptycreate 640 nginx nginxpostrotateif [ -f /var/run/nginx.pid ]; thenkill -USR1 `cat /var/run/nginx.pid`fiendscript
}
2.6 系統安全配置
文件系統安全
# =============================================
# 文件系統安全配置
# =============================================# 設置Nginx相關目錄權限
chown -R root:root /usr/local/nginx
chmod -R 755 /usr/local/nginx# 設置網站目錄權限
chown -R nginx:nginx /usr/local/nginx/html
chmod -R 755 /usr/local/nginx/html# 設置日志目錄權限
chown -R nginx:nginx /var/log/nginx
chmod -R 750 /var/log/nginx# 設置配置文件權限
chmod 640 /usr/local/nginx/conf/*.conf
chmod 600 /usr/local/nginx/conf/ssl/*.key
chmod 644 /usr/local/nginx/conf/ssl/*.crt# 設置臨時目錄權限
chmod 750 /usr/local/nginx/proxy_temp
chmod 750 /usr/local/nginx/fastcgi_temp
chmod 750 /usr/local/nginx/client_body_temp# 設置運行用戶權限
usermod -s /sbin/nologin nginx
usermod -L nginx
防火墻配置
# =============================================
# 防火墻配置
# =============================================# 開放HTTP端口
firewall-cmd --permanent --add-service=http# 開放HTTPS端口
firewall-cmd --permanent --add-service=https# 開放SSH端口(僅內網)
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" service name="ssh" accept'# 限制Nginx狀態頁面訪問
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" port protocol="tcp" port="80" accept'# 阻止惡意IP
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="惡意IP地址" reject'# 重新加載防火墻配置
firewall-cmd --reload# 查看防火墻規則
firewall-cmd --list-all
SELinux配置
# =============================================
# SELinux配置
# =============================================# 檢查SELinux狀態
sestatus# 設置SELinux為寬松模式(臨時)
setenforce 0# 設置SELinux為寬松模式(永久)
sed -i 's/SELINUX=enforcing/SELINUX=permissive/g' /etc/selinux/config# 安裝SELinux管理工具
yum install policycoreutils-python -y# 添加Nginx相關SELinux規則
semanage fcontext -a -t httpd_sys_content_t "/usr/local/nginx/html(/.*)?"
restorecon -Rv /usr/local/nginx/htmlsemanage fcontext -a -t httpd_log_t "/var/log/nginx(/.*)?"
restorecon -Rv /var/log/nginxsemanage fcontext -a -t httpd_config_t "/usr/local/nginx/conf(/.*)?"
restorecon -Rv /usr/local/nginx/conf# 允許Nginx網絡連接
setsebool -P httpd_can_network_connect 1
setsebool -P httpd_can_network_relay 1
setsebool -P httpd_execmem 1
setsebool -P httpd_tty_comm 1
三、性能監控與調優
3.1 性能監控配置
狀態監控配置
# =============================================
# 性能監控配置
# =============================================http {# =============================================# 狀態監控配置# =============================================# 狀態頁面配置server {listen 80;server_name monitor.example.com;# Nginx狀態頁面location /nginx_status {stub_status on;access_log off;allow 127.0.0.1;allow 192.168.1.0/24;deny all;}# 請求監控頁面location /request_status {# 顯示請求處理狀態add_header Content-Type "application/json";return 200 '{"active_connections": $connections_active,"reading": $connections_reading,"writing": $connections_writing,"waiting": $connections_waiting}';access_log off;allow 127.0.0.1;allow 192.168.1.0/24;deny all;}# 系統負載監控location /system_load {# 顯示系統負載信息add_header Content-Type "application/json";return 200 '{"loadavg": "$loadavg","cpu_usage": "$cpu_usage","memory_usage": "$memory_usage"}';access_log off;allow 127.0.0.1;allow 192.168.1.0/24;deny all;}}
}
性能監控腳本
# =============================================
# 性能監控腳本
# 創建 /usr/local/nginx/scripts/monitor.sh
# =============================================#!/bin/bash# Nginx性能監控腳本
# 用法:./monitor.shNGINX_STATUS_URL="http://localhost/nginx_status"
LOG_FILE="/var/log/nginx/performance.log"
ALERT_THRESHOLD=1000# 獲取Nginx狀態
get_nginx_status() {curl -s $NGINX_STATUS_URL
}# 解析Nginx狀態
parse_nginx_status() {local status=$(get_nginx_status)local active_connections=$(echo "$status" | grep "Active connections" | awk '{print $3}')local accepts=$(echo "$status" | awk 'NR==3 {print $1}')local handled=$(echo "$status" | awk 'NR==3 {print $2}')local requests=$(echo "$status" | awk 'NR==3 {print $3}')local reading=$(echo "$status" | awk 'NR==4 {print $2}')local writing=$(echo "$status" | awk 'NR==4 {print $4}')local waiting=$(echo "$status" | awk 'NR==4 {print $6}')echo "Active connections: $active_connections"echo "Accepts: $accepts"echo "Handled: $handled"echo "Requests: $requests"echo "Reading: $reading"echo "Writing: $writing"echo "Waiting: $waiting"# 檢查是否超過閾值if [ "$active_connections" -gt "$ALERT_THRESHOLD" ]; thenecho "WARNING: Active connections exceed threshold: $active_connections > $ALERT_THRESHOLD"# 發送告警(可以集成郵件、短信等)echo "Alert: High active connections detected" | mail -s "Nginx Alert" admin@example.comfi
}# 獲取系統負載
get_system_load() {local loadavg=$(cat /proc/loadavg | awk '{print $1" "$2" "$3}')local cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)local memory_usage=$(free -m | grep "Mem:" | awk '{printf "%.2f", $3/$2*100}')echo "System Load: $loadavg"echo "CPU Usage: $cpu_usage%"echo "Memory Usage: $memory_usage%"
}# 記錄性能數據
log_performance() {local timestamp=$(date "+%Y-%m-%d %H:%M:%S")local status=$(get_nginx_status)local active_connections=$(echo "$status" | grep "Active connections" | awk '{print $3}')local loadavg=$(cat /proc/loadavg | awk '{print $1}')local cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)local memory_usage=$(free -m | grep "Mem:" | awk '{printf "%.2f", $3/$2*100}')echo "$timestamp, $active_connections, $loadavg, $cpu_usage, $memory_usage" >> $LOG_FILE
}# 主函數
main() {echo "=== Nginx Performance Monitor ==="echo "Timestamp: $(date)"echo ""echo "Nginx Status:"parse_nginx_statusecho ""echo "System Load:"get_system_loadecho ""echo "Logging performance data..."log_performanceecho "Monitoring completed."
}# 執行主函數
main
3.2 性能調優建議
基于監控數據的調優
# =============================================
# 性能調優建議腳本
# 創建 /usr/local/nginx/scripts/tune.sh
# =============================================#!/bin/bash# Nginx性能調優建議腳本
# 用法:./tune.sh# 獲取系統信息
get_system_info() {echo "=== System Information ==="echo "CPU Cores: $(nproc)"echo "Memory: $(free -h | grep "Mem:" | awk '{print $2}')"echo "Load Average: $(cat /proc/loadavg | awk '{print $1" "$2" "$3}')"echo ""
}# 獲取Nginx狀態
get_nginx_stats() {echo "=== Nginx Statistics ==="curl -s http://localhost/nginx_statusecho ""
}# 分析性能瓶頸
analyze_performance() {echo "=== Performance Analysis ==="# 獲取活躍連接數local active_connections=$(curl -s http://localhost/nginx_status | grep "Active connections" | awk '{print $3}')echo "Active connections: $active_connections"# 獲取系統負載local load1=$(cat /proc/loadavg | awk '{print $1}')local cpu_cores=$(nproc)local load_per_core=$(echo "$load1 / $cpu_cores" | bc -l)echo "Load per core: $load_per_core"# 獲取內存使用率local memory_usage=$(free -m | grep "Mem:" | awk '{printf "%.2f", $3/$2*100}')echo "Memory usage: $memory_usage%"# 分析建議echo ""echo "=== Tuning Recommendations ==="# 連接數建議if [ "$active_connections" -gt 1000 ]; thenecho "1. Increase worker_connections: recommend 65535"echo "2. Consider adding more worker processes"fi# 負載建議if (( $(echo "$load_per_core > 1.0" | bc -l) )); thenecho "3. High load detected: consider optimizing application or adding more servers"fi# 內存建議if (( $(echo "$memory_usage > 80" | bc -l) )); thenecho "4. High memory usage: check for memory leaks or optimize caching"fiecho ""
}# 生成優化配置
generate_optimized_config() {echo "=== Optimized Configuration ==="# 獲取CPU核心數local cpu_cores=$(nproc)# 生成優化配置cat << EOF
# Optimized Nginx Configuration
# Generated on $(date)worker_processes $cpu_cores;
worker_cpu_affinity auto;
worker_rlimit_nofile 65535;events {worker_connections 65535;use epoll;multi_accept on;
}http {sendfile on;tcp_nopush on;tcp_nodelay on;keepalive_timeout 65;keepalive_requests 1000;client_body_buffer_size 128k;client_max_body_size 50m;gzip on;gzip_comp_level 6;gzip_min_length 1k;gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;open_file_cache max=100000 inactive=20s;open_file_cache_valid 30s;open_file_cache_min_uses 2;open_file_cache_errors on;
}
EOF
}# 主函數
main() {echo "Nginx Performance Tuning Assistant"echo "=================================="echo ""get_system_infoget_nginx_statsanalyze_performancegenerate_optimized_configecho "Tuning analysis completed."echo "Please review the recommendations and apply them carefully."
}# 執行主函數
main
性能優化關鍵點:
- 合理配置工作進程和連接數
- 選擇合適的事件模型
- 啟用緩存和壓縮
- 優化系統內核參數
- 監控和調優性能瓶頸
安全配置關鍵點:
- 隱藏敏感信息
- 配置安全頭信息
- 啟用SSL/TLS加密
- 實施訪問控制
- 防護常見攻擊
- 安全日志管理
通過本文的學習,你應該能夠獨立完成Nginx的性能優化和安全配置,打造一個既高性能又安全的Web服務器環境。記住,性能優化和安全配置是一個持續的過程,需要根據實際運行情況進行不斷調整和優化。