Nginx 配置 Https

系统环境

1
2
CentOS Linux release 7.6.1810 (Core)
Linux 3.10.0-957.12.2.el7.x86_64 #1 SMP Tue May 14 21:24:32 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

系统安装 OpenSSL

1
2
3
4
5
# 更新系统
# yum update

# 安装openssl
# yum install openssl openssl-devel

Nginx 安装 SSL 模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 配置编译
# ./configure \
--user=nginx \
--group=nginx \
--prefix=/usr/local/nginx \
--with-http_ssl_module \
--with-http_realip_module \
--with-http_concat_module \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--with-http_upstream_consistent_hash_module

# 编译安装,会覆盖已安装的Nginx
# make && make install

Nginx 配置 SSL 证书与 SSL 性能调优

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

# SSL证书
ssl on;
ssl_certificate /usr/local/nginx/cert/example.cn.crt;
ssl_certificate_key /usr/local/nginx/cert/example.cn.key;

# SSL性能调优
ssl_session_timeout 10m;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDHE-RSA-AES256-SHA384:AES256-SHA256:RC4:HIGH:!MD5:!aNULL:!eNULL:!NULL:!DH:!EDH:!AESGCM;

...(省略)
}

Nginx 配置 Http 跳转 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
# 第一种写法
server {
listen 80;
server_name www.example.cn;
rewrite ^(.*) https://$server_name$1 permanent;
}

# 第二种写法,将http的url通过301状态码重定向到https的url上
server {
listen 80;
server_name www.example.cn;
return 301 https://$server_name$request_uri;
}

server {
listen 443;
server_name www.example.cn;

# SSL性能调优
ssl_session_timeout 10m;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDHE-RSA-AES256-SHA384:AES256-SHA256:RC4:HIGH:!MD5:!aNULL:!eNULL:!NULL:!DH:!EDH:!AESGCM;

...(省略)
}

Nginx 配置支持同时访问 80 和 443 端口

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

if ($server_port !~ 443){
rewrite ^(/.*)$ https://$host$1 permanent;
}

# SSL证书
# ssl on; # 注释掉
ssl_certificate /usr/local/nginx/cert/example.cn.crt;
ssl_certificate_key /usr/local/nginx/cert/example.cn.key;

# SSL性能调优
ssl_session_timeout 10m;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDHE-RSA-AES256-SHA384:AES256-SHA256:RC4:HIGH:!MD5:!aNULL:!eNULL:!NULL:!DH:!EDH:!AESGCM;

...(省略)
}