安装

ubuntu 源可以直接使用 apt install nginx,安装完成后需要防火墙放行相应端口。

1
2
firewall-cmd --permanent --add-service=https
firewall-cmd --permanent --add-service=http

配置 443 端口

监听 443 端口,然后配置长连接代理到内部端口上:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
server {
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;

include /etc/nginx/conf.d/snippets/ssl.conf;

server_name localhost;

# 配置 websocket 长连接
location ^~ / {
proxy_pass https://127.0.0.1:9090/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header Host $host;
}
}

配置 ssl 证书:

1
2
3
4
5
6
7
8
9
10
11
ssl_certificate /etc/ssl/certs/server.crt;
ssl_certificate_key /etc/ssl/private/server.key;
# ssl_dhparam /etc/ssl/certs/dhparam.pem;

ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
ssl_ecdh_curve secp384r1;
ssl_session_tickets off;
resolver 114.114.114.114 221.130.252.200 valid=300s;
resolver_timeout 5s;

使用 OpenSSL 制作 X.509 证书

1
2
3
4
5
6
7
8
9
10
11
# 生成自签名根证书(即顶级CA)
openssl req -new -x509 -days 5480 -keyout CA.key -out CA.crt

# 生成服务器私钥
openssl genrsa -out server.key 2048

# 用服务器私钥生成服务器用的证书( csr 文件)
openssl req -key server.key -out server.csr

# 为 csr 文件签名
openssl ca -in server.csr -out server.crt -cert CA.crt -keyfile CA.key

使用OpenSSL工具制作X.509证书的方法及其注意事项总结

配置 80 端口跳转

Nginx 带有重定向选项,配置监听 80 端口,然后重定向到 443 即可。

1
2
3
4
5
server {
listen 80;
server_name localhost;
rewrite ^(.*)$ https://$host$1 permanent;
}