nginx 常用配置

配置 ssl 证书

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
server {
listen 443 ssl;
server_name *.example.com;

ssl_certificate "../ssl/example.com/full_chain.pem";
ssl_certificate_key "../ssl/example.com/private.key";

location / {
# root ./html/dist;
proxy_pass http://localhost:8080/; # 代理到本地的 8080 端口
}

error_page 502 /502.html;
location = /502.html {
root html;
}
}

配置 api 代理

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
server {
listen 443 ssl;
server_name *.example.com;

ssl_certificate "../ssl/example.com/full_chain.pem";
ssl_certificate_key "../ssl/example.com/private.key";

location / {
# root ./html/dist;
proxy_pass http://localhost:8080/; # 代理到本地的 8080 端口
}

# api 代理
location /ApiPath/ {
# http -> https
proxy_pass http://192.168.1.1:8081/;
}

# websocket 代理
location /ApiPath/ {
# ws -> wss 前缀都是 http:// 修改 IP、port 配置就行
proxy_pass http://192.168.1.1:8081/;

# WebSocket 指定 tcp 协议版本
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $http_connection;
# 若某些 nginx 版本/后端出问题,可改为:
# proxy_set_header Connection "Upgrade";

# 关闭缓冲(WebSocket 一般关闭缓冲)
proxy_buffering off;
}

error_page 502 /502.html;
location = /502.html {
root html;
}
}

文件预览

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
server {
listen 8082;
charset utf-8;

root ./files;
index index_nonexistent.html; # 一个不存在的文件

location / {
# 设置允许跨域的域,* 表示允许任何域,也可以设置特定的域
add_header 'Access-Control-Allow-Origin' '*';

# 开启文件预览功能
autoindex on;
# 文件大小统计
autoindex_exact_size on;
# 文件修改日期
autoindex_localtime on;
}
}

挂载自定义脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
server {
listen 8082;

# 指向本地脚本文件
location /custom-script.js {
alias D:/nginx-1.19.7/conf/custom-script.js;

types {
application/javascript js;
}
}

location / {
root ./html/dist;

# 挂载自定义脚本
sub_filter '</body>' '<script src="/custom-script.js"></script></body>';
sub_filter_once on;
}
}

Windows Cmd 终止所有 Nginx

1
taskkill /F /IM nginx.exe

linux 终止 Nginx

1
nginx -s stop