引言

Nginx是高性能的Web服务器和反向代理。本文介绍Nginx的配置和优化。

一、基础配置

1.1 配置文件结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 全局配置
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

# 事件模块
events {
worker_connections 1024;
use epoll;
}

# HTTP模块
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;
keepalive_timeout 65;

# 服务器配置
include /etc/nginx/conf.d/*.conf;
}

1.2 虚拟主机配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
server {
listen 80;
server_name example.com www.example.com;

# 根目录
root /var/www/html;
index index.html index.htm;

# 位置匹配
location / {
try_files $uri $uri/ =404;
}

# 静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
}

# 日志
access_log /var/log/nginx/example.access.log;
error_log /var/log/nginx/example.error.log;
}

二、反向代理

2.1 基本代理

1
2
3
4
5
6
7
8
9
10
11
12
server {
listen 80;
server_name api.example.com;

location / {
proxy_pass http://127.0.0.1:8080;
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;
}
}

2.2 负载均衡

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
upstream backend {
# 轮询(默认)
server 192.168.1.10:8080;
server 192.168.1.11:8080;

# 加权轮询
# server 192.168.1.10:8080 weight=3;
# server 192.168.1.11:8080 weight=1;

# IP哈希
# ip_hash;

# 最少连接
# least_conn;

# 健康检查
server 192.168.1.10:8080 max_fails=3 fail_timeout=30s;
}

server {
listen 80;
server_name lb.example.com;

location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}

三、HTTPS配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
server {
listen 443 ssl http2;
server_name example.com;

# SSL证书
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;

# SSL协议和加密套件
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;

# SSL会话缓存
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;

location / {
root /var/www/html;
index index.html;
}
}

# HTTP重定向到HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}

四、缓存配置

4.1 代理缓存

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 缓存路径
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g
inactive=60m use_temp_path=off;

server {
location / {
proxy_cache my_cache;
proxy_cache_valid 200 60m;
proxy_cache_valid 404 1m;
proxy_cache_bypass $http_cache_control;

add_header X-Cache-Status $upstream_cache_status;

proxy_pass http://backend;
}
}

4.2 浏览器缓存

1
2
3
4
5
6
7
8
9
location ~* \.(jpg|jpeg|png|gif|ico)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}

location ~* \.(css|js)$ {
expires 7d;
add_header Cache-Control "public";
}

五、性能优化

5.1 基础优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 工作进程数
worker_processes auto;

# 工作进程优先级
worker_priority -5;

# 工作进程CPU亲和性
worker_cpu_affinity auto;

# 最大连接数
events {
worker_connections 10240;
use epoll;
multi_accept on;
}

# 文件缓存
open_file_cache max=10000 inactive=30s;
open_file_cache_valid 60s;
open_file_cache_min_uses 2;
open_file_cache_errors on;

5.2 Gzip压缩

1
2
3
4
5
6
7
8
9
10
11
http {
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml text/javascript
application/json application/javascript application/xml+rss
application/rss+xml font/truetype font/opentype
application/vnd.ms-fontobject image/svg+xml;
gzip_disable "msie6";
}

5.3 连接优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 长连接
keepalive_timeout 65;
keepalive_requests 100;

# 上游长连接
upstream backend {
server 127.0.0.1:8080;
keepalive 32;
}

server {
location / {
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_pass http://backend;
}
}

六、安全配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 隐藏版本号
server_tokens off;

# 限制请求大小
client_max_body_size 10m;

# 防止DDOS
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
limit_req zone=one burst=5;

# 防止盗链
location ~* \.(gif|jpg|png)$ {
valid_referers none blocked example.com *.example.com;
if ($invalid_referer) {
return 403;
}
}

# 安全头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;

七、日志管理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 日志格式
log_format main '$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';

# 访问日志
access_log /var/log/nginx/access.log main buffer=32k;

# 错误日志
error_log /var/log/nginx/error.log warn;

# 关闭特定位置的日志
location = /favicon.ico {
access_log off;
log_not_found off;
}

总结

Nginx核心配置:

  1. 反向代理:转发请求到后端服务
  2. 负载均衡:多种算法分发请求
  3. HTTPS:SSL/TLS加密传输
  4. 缓存:提升响应速度
  5. 性能优化:连接、压缩、缓存
  6. 安全加固:限流、防盗链

参考资料