1. Nginx基础配置与核心模块解析
Nginx作为现代Web架构的核心组件,其基础配置决定了服务的稳定性和扩展性。我们先从最核心的配置项开始拆解:
主配置文件结构通常位于/etc/nginx/nginx.conf,采用模块化设计。一个生产环境的基础配置应包含以下关键块:
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
use epoll;
multi_accept on;
}
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;
sendfile on;
tcp_nopush on;
keepalive_timeout 65;
include /etc/nginx/conf.d/*.conf;
}
关键模块解析:
- ngx_http_core_module:定义HTTP服务基础参数,如
sendfile开启零拷贝传输 - ngx_http_log_module:定制化日志格式,实测发现开启
gzip后日志体积可减少60% - ngx_http_ssl_module:配置HTTPS加密,推荐使用TLS 1.3版本
- ngx_http_gzip_module:静态资源压缩,对文本内容压缩率可达70%+
虚拟主机配置示例:
server {
listen 80;
server_name example.com;
root /var/www/html;
location / {
index index.html;
try_files $uri $uri/ =404;
}
location ~* \.(jpg|png|gif)$ {
expires 30d;
add_header Cache-Control "public";
}
}
2. 反向代理与负载均衡实战
Nginx作为反向代理时,其核心价值在于请求分发和流量管控。以下是经过百万级并发验证的配置方案:
基础反向代理配置:
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_connect_timeout 3s;
proxy_read_timeout 10s;
proxy_send_timeout 10s;
# 缓冲区优化
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 16k;
}
负载均衡策略对比:
| 算法类型 | 配置指令 | 适用场景 | 优缺点 |
|---|


3468

被折叠的 条评论
为什么被折叠?



