1. 什么是 HTTPS?

HTTPS(超文本传输安全协议)是 HTTP 的加密版本,通过 SSL/TLS 协议来确保数据传输的安全性。也就是说,别人不能轻易地偷看你们之间的通信内容啦!

2. HTTPS 配置流程

步骤 1: 获取 SSL 证书

首先你需要一个 SSL 证书。这个证书就像是网站的“身份证”,能保证访问者正在访问的确实是你的网站哦!你有两个选择:

  • 购买 SSL 证书:许多域名提供商(如 Namecheap、GoDaddy)都有提供。
  • 使用免费 SSL 证书:推荐使用 Let’s Encrypt,这是一个免费的证书颁发机构(CA),超棒的!

步骤 2: 安装 SSL 证书

获得证书后,要把它安装到你的服务器上。安装的具体方法取决于你的网站服务器种类,我们来看常见的两种情况。

a. Nginx 服务器

  1. 将 SSL 证书和私钥上传到服务器。
  2. 修改 Nginx 配置文件(通常在 /etc/nginx/sites-available/ 里面):
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;
server_name example.com www.example.com;
return 301 https://$host$request_uri; # 重定向到 https
}

server {
listen 443 ssl;
server_name example.com www.example.com;

ssl_certificate /path/to/ssl/certificate.crt;
ssl_certificate_key /path/to/private/key.key;

# 启用 HTTPS 的一些推荐配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;

location / {
# 网站的根目录
root /var/www/html;
index index.html;
}
}
  1. 保存配置,然后重启 Nginx:
1
sudo systemctl restart nginx

b. Apache 服务器

  1. 打开 Apache 配置文件(通常在 /etc/apache2/sites-available/ 里面):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<VirtualHost *:80>
ServerName example.com
Redirect permanent / https://example.com/
</VirtualHost>

<VirtualHost *:443>
ServerName example.com

SSLEngine on
SSLCertificateFile /path/to/ssl/certificate.crt
SSLCertificateKeyFile /path/to/private/key.key
SSLCertificateChainFile /path/to/ca_bundle.crt

DocumentRoot /var/www/html
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
  1. 启用 SSL 模块并重启 Apache:
1
2
sudo a2enmod ssl
sudo systemctl restart apache2

步骤 3: 强制 HTTPS

虽然你已经配置好 HTTPS 了,但是还需要确保所有用户都通过 HTTPS 来访问你的站点呢~ 最简单的方法就是在 Nginx 或 Apache 里设置 301 重定向,前面我们已经有提到啦,就是那个把 HTTP 重定向到 HTTPS 的部分。

步骤 4: 测试你的 HTTPS

哇,终于配置好了!接下来打开浏览器,访问你的网站 https://your-domain.com,看看是不是成功显示一个小锁头🔒啦?如果有小锁头,恭喜你,HTTPS 配置成功!

别忘了用在线工具 SSL Labs 来测试你的 SSL 证书是否配置得完美哦~

tomcat配置证书和Nginx配置https证书有何区别?