Nginx证书生成及使用

证书来源

1.通过阿里云/腾讯云等第三方服务商购买

免费版, 一般限制一年的有效期

2.使用OpenSSL生成证书文件

1
2
3
4
5
6
7
8
9
10
mkdri /root/cert
cd /root/cert
openssl genrsa -des3 -out server.key 1024
# 设定密码
openssl req -new -key server.key -out server.csr
# 输入密码, 验证信息
cp server.key server.key.org
openssl rsa -in server.key.org -out server.key
# 验证密码
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

生成文件: server.key | server.crt

开启SSL实例

详细官方文档: https://nginx.org/en/docs/http/ngx_http_ssl_module.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
server{
# ssl on;
listen 443 ssl;
server_name localhost;

ssl_certificate server.crt; # 指定证书文件路径
ssl_certificate_key server.key; # 指定证书key文件路径

ssl_session_cache shared:SSL:1m; # 配置用于SSL会话缓存
# off-禁用, 客户端不得重复使用会话
# none-禁用, 客户端可以重复使用, 但并没有在缓存中存储会话参数
# builtin-内置OpenSSL缓存,仅在一个工作进程中使用
# shared-所有工作进程间共享缓存, 相关信息由name和size指定
ssl_session_timeout 5m; # 开启会话后,客户端能够反复使用存储会话时间

ssl_ciphers HIGH:!aNULL:!MD5; # 允许密码格式,可以用openssl ciphers查看支持格式
ssl_prefer_server_ciphers on; # 指定是否服务器密码优先于客户端密码

location /{
root html;
index index.html index.htm;
}
}

自动转换为https协议

1
2
3
4
5
6
7
8
9
10
11
12
location /{
...
rewrite ^(.*) https://[server_name]$1;
}



server {
if ($host = [server_name]) {
return 301 https://$host$request_uri;
}
}