1. Nginx入门:从下载到配置的完整指南
Nginx作为一款高性能的HTTP和反向代理服务器,已经成为现代Web架构中不可或缺的组件。我第一次接触Nginx是在2013年为一个电商项目做性能优化时,当时Apache在高并发场景下表现不佳,切换到Nginx后QPS直接提升了3倍。本文将带你完整走一遍Nginx的安装配置流程,包含我在实际运维中积累的实用技巧。
2. Nginx下载与安装
2.1 官方下载渠道选择
Nginx官网(nginx.org)提供了稳定版(Stable)和主线版(Mainline)两个版本分支。对于生产环境,我强烈建议使用稳定版。以下是各平台的下载建议:
-
Linux:优先使用官方预编译包
bash复制# Ubuntu/Debian sudo apt install curl gnupg2 ca-certificates lsb-release echo "deb http://nginx.org/packages/ubuntu `lsb_release -cs` nginx" | sudo tee /etc/apt/sources.list.d/nginx.list curl -fsSL https://nginx.org/keys/nginx_signing.key | sudo apt-key add - sudo apt update sudo apt install nginx # CentOS/RHEL sudo yum install yum-utils sudo vi /etc/yum.repos.d/nginx.repo添加以下内容:
code复制[nginx-stable] name=nginx stable repo baseurl=http://nginx.org/packages/centos/$releasever/$basearch/ gpgcheck=1 enabled=1 gpgkey=https://nginx.org/keys/nginx_signing.key module_hotfixes=true -
Windows:官网提供zip包,解压即可使用
-
macOS:推荐使用Homebrew安装
bash复制
brew install nginx
注意:切勿从第三方不明来源下载Nginx,曾有案例发现植入后门的修改版
2.2 编译安装的进阶选项
当需要自定义模块或优化性能时,编译安装是更好的选择。这是我常用的编译参数:
bash复制./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_ssl_module \
--with-http_realip_module \
--with-http_stub_status_module \
--with-threads \
--with-file-aio \
--with-http_v2_module \
--with-http_gzip_static_module
关键参数说明:
--with-threads:启用线程池提升性能--with-file-aio:启用异步IO--with-http_v2_module:支持HTTP/2--with-http_gzip_static_module:预压缩静态文件
编译完成后执行:
bash复制make && make install
3. Nginx配置文件深度解析
3.1 核心配置文件结构
Nginx配置文件默认位于/etc/nginx/nginx.conf(Linux)或安装目录下的conf/nginx.conf(Windows)。其结构主要分为:
-
Main Context(全局配置)
nginx复制user nginx; worker_processes auto; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; -
Events Context(连接处理配置)
nginx复制events { worker_connections 1024; use epoll; # Linux高性能事件模型 multi_accept on; } -
HTTP Context(HTTP服务配置)
nginx复制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; tcp_nodelay on; keepalive_timeout 65; include /etc/nginx/conf.d/*.conf; }
3.2 Server块配置详解
每个server块定义一个虚拟主机,这是我的生产环境配置模板:
nginx复制server {
listen 80;
server_name example.com www.example.com;
# 强制HTTPS
if ($scheme = http) {
return 301 https://$server_name$request_uri;
}
}
server {
listen 443 ssl http2;
server_name example.com www.example.com;
ssl_certificate /etc/ssl/certs/example.com.crt;
ssl_certificate_key /etc/ssl/private/example.com.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
root /var/www/example.com;
index index.html index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 365d;
add_header Cache-Control "public, no-transform";
}
# 禁止访问隐藏文件
location ~ /\. {
deny all;
}
}
3.3 Location匹配规则精要
Nginx的location匹配是配置中最容易出错的部分,优先级规则如下:
=精确匹配nginx复制location = /logo.png { ... }^~前缀匹配(停止正则检查)nginx复制location ^~ /images/ { ... }~和~*正则匹配(区分大小写/不区分)nginx复制location ~ \.php$ { ... }- 普通前缀匹配
nginx复制location / { ... }
经验:静态文件应该用
^~前缀匹配避免不必要的正则检查
4. 性能优化关键参数
4.1 工作进程优化
nginx复制worker_processes auto; # 通常设为CPU核心数
worker_cpu_affinity auto; # CPU亲和性
worker_rlimit_nofile 65535; # 文件描述符限制
4.2 连接处理优化
nginx复制events {
worker_connections 4096; # 单个worker最大连接数
use epoll; # Linux高性能事件模型
multi_accept on; # 一次性接受所有新连接
accept_mutex off; # 高流量时关闭互斥锁
}
4.3 缓冲与超时设置
nginx复制http {
client_body_buffer_size 16k;
client_header_buffer_size 1k;
client_max_body_size 10m;
large_client_header_buffers 4 8k;
send_timeout 60s;
client_body_timeout 60s;
client_header_timeout 60s;
keepalive_timeout 75s;
}
5. 常见问题排查指南
5.1 配置语法检查
每次修改配置后必须执行:
bash复制nginx -t
输出示例:
code复制nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
5.2 性能问题排查
-
检查活跃连接
bash复制netstat -anp | grep nginx | wc -l -
监控worker进程
bash复制top -p $(pgrep -d',' nginx) -
分析慢请求
nginx复制log_format timed_combined '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" ' '$request_time $upstream_response_time $pipe';
5.3 常见错误代码
403 Forbidden:检查文件权限和SELinux上下文502 Bad Gateway:后端服务是否正常运行504 Gateway Timeout:增加proxy_read_timeout值
6. 实用配置片段
6.1 反向代理配置
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 60s;
proxy_read_timeout 600s;
proxy_send_timeout 600s;
proxy_buffer_size 16k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
}
6.2 负载均衡配置
nginx复制upstream backend {
least_conn; # 最少连接算法
server 10.0.0.1:8080 weight=5;
server 10.0.0.2:8080;
server 10.0.0.3:8080 max_fails=3 fail_timeout=30s;
keepalive 32; # 保持连接池大小
}
6.3 安全加固配置
nginx复制server {
# 禁用不安全的HTTP方法
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
# 防止点击劫持
add_header X-Frame-Options "SAMEORIGIN";
# XSS防护
add_header X-XSS-Protection "1; mode=block";
# 禁止MIME类型嗅探
add_header X-Content-Type-Options "nosniff";
# CSP策略
add_header Content-Security-Policy "default-src 'self'";
}
7. 调试与日志分析技巧
7.1 自定义日志格式
nginx复制log_format debug_log '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'ReqTime:$request_time Upstream:$upstream_response_time '
'Host:$host Server:$server_addr';
7.2 条件日志记录
nginx复制# 只记录5xx错误
map $status $loggable {
~^[23] 0;
default 1;
}
access_log /var/log/nginx/error_requests.log combined if=$loggable;
7.3 实时监控命令
bash复制# 实时查看访问日志
tail -f /var/log/nginx/access.log | awk '{print $1}' | sort | uniq -c | sort -nr
# 统计HTTP状态码
awk '{print $9}' access.log | sort | uniq -c | sort -rn
# 找出最耗时的请求
awk '{print $NF,$7}' access.log | sort -rn | head -20
8. 动态模块加载
Nginx 1.9.11+支持动态模块,无需重新编译:
bash复制# 查看已安装模块
nginx -V 2>&1 | grep --color -o "with-http_[a-z0-9_]*"
# 加载动态模块
load_module modules/ngx_http_geoip_module.so;
9. 配置管理最佳实践
-
模块化配置:使用
include拆分配置nginx复制include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; -
版本控制:将配置纳入Git管理
bash复制
/etc/nginx/ ├── nginx.conf ├── conf.d/ ├── sites-available/ ├── sites-enabled/ -> ../sites-available -
配置校验自动化:设置Git钩子
bash复制# .git/hooks/pre-commit #!/bin/sh nginx -t || exit 1
10. 容器化部署方案
10.1 Docker基础镜像
dockerfile复制FROM nginx:1.23-alpine
# 移除默认配置
RUN rm /etc/nginx/conf.d/default.conf
# 添加自定义配置
COPY nginx.conf /etc/nginx/nginx.conf
COPY conf.d/ /etc/nginx/conf.d/
# 添加静态文件
COPY public/ /usr/share/nginx/html/
# 设置非root用户运行
RUN chown -R nginx:nginx /var/cache/nginx && \
chown -R nginx:nginx /usr/share/nginx/html
USER nginx
EXPOSE 8080
10.2 Kubernetes配置示例
yaml复制apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
spec:
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.23-alpine
ports:
- containerPort: 80
volumeMounts:
- name: nginx-config
mountPath: /etc/nginx/nginx.conf
subPath: nginx.conf
- name: nginx-config
mountPath: /etc/nginx/conf.d
volumes:
- name: nginx-config
configMap:
name: nginx-config
11. 性能测试与调优
11.1 基准测试工具
bash复制# 安装wrk
sudo apt install wrk
# 执行测试
wrk -t4 -c1000 -d60s --latency http://example.com
参数说明:
-t:线程数-c:连接数-d:测试时长--latency:显示延迟分布
11.2 内核参数调优
bash复制# 增加本地端口范围
echo "net.ipv4.ip_local_port_range = 1024 65535" >> /etc/sysctl.conf
# 增加文件描述符限制
echo "fs.file-max = 2097152" >> /etc/sysctl.conf
echo "* soft nofile 65535" >> /etc/security/limits.conf
echo "* hard nofile 65535" >> /etc/security/limits.conf
# 应用修改
sysctl -p
12. 高级功能实现
12.1 灰度发布配置
nginx复制# 基于Cookie的灰度发布
map $cookie_gray $group {
default "production";
"true" "gray";
}
upstream production {
server 10.0.0.1:8080;
server 10.0.0.2:8080;
}
upstream gray {
server 10.0.0.3:8080;
}
server {
location / {
proxy_pass http://$group;
}
}
12.2 地理限制访问
nginx复制geo $blocked_country {
default 0;
CN 1;
RU 1;
}
server {
if ($blocked_country) {
return 403;
}
}
12.3 动态内容缓存
nginx复制proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m;
server {
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;
add_header X-Proxy-Cache $upstream_cache_status;
}
}
