Nginx作为现代Web架构的核心组件,其设计哲学源于C10K问题(即单机同时处理1万个连接)的解决方案。与传统Apache的进程/线程模型不同,Nginx采用事件驱动的异步架构:
这种架构使得在2核4G的普通服务器上,Nginx可轻松应对5万+的并发连接。实测数据显示,相同硬件条件下,Nginx的静态文件处理能力是Apache的5-10倍。
生产环境建议:worker_processes设置为CPU核心数,worker_connections建议值= worker_processes × 1024
nginx复制server {
listen 3128;
resolver 8.8.8.8;
location / {
proxy_pass http://$http_host$request_uri;
proxy_set_header Host $http_host;
# 代理认证配置
auth_basic "Proxy Authentication";
auth_basic_user_file /etc/nginx/conf.d/proxy.passwd;
}
}
关键点:
nginx复制upstream backend {
least_conn; # 最少连接算法
server 192.168.1.101:8080 weight=3;
server 192.168.1.102:8080;
server 192.168.1.103:8080 backup;
}
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://backend;
proxy_set_header X-Real-IP $remote_addr;
proxy_next_upstream error timeout http_500;
}
}
核心优势:
现代Web应用通常采用如下架构:
code复制location ~* \.(jpg|png|gif|css|js)$ {
root /data/static;
expires 30d;
access_log off;
add_header Cache-Control "public";
}
location ~ \.php$ {
fastcgi_pass php-fpm:9000;
include fastcgi_params;
}
性能优化要点:
推荐编译参数(以Nginx 1.25.3为例):
bash复制./configure \
--prefix=/opt/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-jit \
--with-file-aio \
--with-threads \
--with-stream \
--with-cc-opt='-O3 -march=native -DTCP_FASTOPEN=23'
关键模块说明:
--with-pcre-jit:启用正则表达式JIT编译,提升rewrite性能--with-file-aio:异步文件I/O,适合大文件传输-DTCP_FASTOPEN:启用TCP快速打开(需内核3.7+支持)conf复制net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65536
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
conf复制nginx soft nofile 65535
nginx hard nofile 65535
nginx复制server_tokens off;
nginx复制if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
nginx复制location ~* /(\.git|\.svn|\.env|config\.php) {
deny all;
}
推荐目录结构:
code复制/opt/nginx/
├── conf/
│ ├── nginx.conf # 主配置
│ ├── sites-enabled/ # 启用的虚拟主机
│ ├── sites-available/ # 可用虚拟主机
│ ├── modules-enabled/ # 动态模块
│ └── includes/ # 公共配置片段
│ ├── gzip.conf
│ ├── security.conf
│ └── proxy.conf
主配置文件片段:
nginx复制http {
include /opt/nginx/conf/includes/*.conf;
include /opt/nginx/conf/sites-enabled/*.conf;
}
nginx复制location /static/ {
alias /data/assets/; # 注意:alias路径需要以/结尾
}
# 请求/static/file.txt 实际访问/data/assets/file.txt
nginx复制location ~ /images/ {
# 正则匹配,优先级低于^~
}
location ^~ /images/ {
# 优先匹配此规则
}
nginx复制log_format main_ext '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$http_x_forwarded_for" "$request_time" '
'"$upstream_response_time"';
bash复制#!/bin/bash
tail -f /var/log/nginx/access.log | awk '
BEGIN {
print "HTTP状态码统计"
}
{
codes[$9]++;
total++
}
END {
for(code in codes)
printf "%s: %d (%.2f%%)\n", code, codes[code], 100*codes[code]/total
}'
bash复制watch -n 1 "netstat -ant | grep :80 | awk '{print \$6}' | sort | uniq -c"
bash复制goaccess /var/log/nginx/access.log --log-format=COMBINED
nginx复制location / {
proxy_pass http://backend;
proxy_next_upstream_timeout 2s;
proxy_connect_timeout 1s;
proxy_read_timeout 3s;
}
排查步骤:
nginx复制proxy_buffer_size 16k;
proxy_buffers 4 32k;
检查方向:
通过map实现按比例分流:
nginx复制map $cookie_userid $backend {
default "production";
~^(?<id>\d+)$ "canary";
}
upstream production {
server 192.168.1.100:8080;
}
upstream canary {
server 192.168.1.200:8080;
}
server {
location / {
proxy_pass http://$backend;
}
}
nginx复制stream {
upstream db_cluster {
server 10.0.1.101:3306;
server 10.0.1.102:3306;
}
server {
listen 3306;
proxy_pass db_cluster;
}
}
nginx复制location /user-service/ {
rewrite ^/user-service/(.*) /$1 break;
proxy_pass http://user-service;
}
location /order-service/ {
rewrite ^/order-service/(.*) /$1 break;
proxy_pass http://order-service;
}
nginx复制location /ws/ {
proxy_pass http://websocket_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 86400;
}
经过多年运维实践,我认为Nginx配置的核心原则是:简单即美。过度复杂的配置往往带来维护成本指数级上升。建议定期使用nginx -T导出完整配置进行版本化管理,并通过自动化测试验证配置变更。