Nginx 配置文件

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
worker_processes auto;  # 指定 Nginx 使用的 worker 进程数量,auto 表示按照 CPU 核心数自动分配

error_log /var/log/nginx/error.log; # 指定错误日志文件路径
pid /run/nginx.pid; # 指定进程 ID 文件路径

events {
worker_connections 1024; # 每个 worker 进程允许的最大连接数
}

http {
include /etc/nginx/mime.types; # 引入 MIME 类型列表

default_type application/octet-stream; # 默认 MIME 类型

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; # 开启 sendfile 系统调用以提高文件传输效率

keepalive_timeout 65; # 长连接超时时间

# gzip 压缩设置
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

# 虚拟主机配置示例
server {
listen 80; # 监听的端口号

server_name example.com; # 域名或 IP 地址

root /var/www/html; # 根目录

index index.html index.htm; # 默认首页文件名

# 静态文件缓存配置
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2|ttf)$ {
expires 30d;
add_header Cache-Control "public, max-age=2592000, immutable";
}

# 路由配置
location /api/ {
proxy_pass http://localhost:3000/; # 将请求转发到 Node.js 服务
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}

# 404 页面
error_page 404 /404.html;

# 5xx 错误页面
error_page 500 502 503 504 /50x.html;

# 自定义错误页面路径
location = /404.html {
root /usr/share/nginx/html;
internal;
}

location = /50x.html {
root /usr/share/nginx/html;
internal;
}

# HTTPS 配置示例
listen 443 ssl; # HTTPS 监听端口号
ssl_certificate /path/to/cert.pem; # SSL 证书文件路径
ssl_certificate_key /path/to/key.pem; # SSL 证书密钥文件路径

# 强制 HTTPS
if ($scheme != "https") {
return 301 https://$server_name$request_uri;
}
}
}