0%

Nginx网站配置TLS证书

本文记录为已搭建的网站配置TLS证书,使自己的网站支持https访问。

条件准备:已安装Nginx的服务器一个

1. 申请证书

证书的申请可以在阿里云搜索SSL证书,申请好之后可以看到如下界面,点击右边的下载获得证书文件,下载得到的文件有两个文件domainName.key和domainName.pem,申请好的证书下载界面如下

2. 上传证书到服务器

创建证书目录存在申请的证书
mkdir /etc/nginx/cert
创建完成后将申请的证书文件保存在此目录下

3、配置Nginx

Nginx的配置文件一般位于/etc/nginx/sites-available/default

常规的http访问是80或者8080端口,而https访问默认是443端口。

由于很多人习惯http访问,我们可根据需要进行强制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
28
29
30
31
32
33
34
35
36
37
38
39
server {
listen 443 ssl; #SSL协议访问端口号为443。此处如未添加ssl,可能会造成Nginx无法启动。
server_name www.example.com; #将localhost修改为您证书绑定的域名,例如:www.example.com。

ssl_certificate /etc/nginx/cert/www.example.com.pem; #将domain name.pem替换成您证书的文件名。
ssl_certificate_key /etc/nginx/cert/www.example.com.key; #将domain name.key替换成您证书的密钥文件名。
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4; #使用此加密套件。
ssl_protocols TLSv1.2; #使用该协议进行配置。
ssl_prefer_server_ciphers on;

root /var/www/www.example.com;
# Add index.php to the list if you are using PHP
index index.php index.html index.htm index.nginx-debian.html;

location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
}

# pass PHP scripts to FastCGI server
#
location ~ \.php$ {
include snippets/fastcgi-php.conf;
#
# # With php-fpm (or other unix sockets):
fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
# # With php-cgi (or other tcp sockets):
# fastcgi_pass 127.0.0.1:9000;
}
}

#设置http强制跳转https
server {
listen 80;
server_name www.example.com; #将localhost修改为您证书绑定的域名,例如:www.example.com。
rewrite ^(.*)$ https://www.example.com$1 permanent; #将所有http请求通过rewrite重定向到https。
}

4、测试与重启

测试语法是否正确

1
nginx -t

如果出现以下信息表示配置成功

1
2
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

重启

1
nginx -s reload