CentOS 设置 HTTPS

随着互联网安全意识的不断提高,HTTPS已经成为网站安全的基本要求,CentOS 作为一款流行的Linux发行版,设置 HTTPS 是保证网站安全的重要步骤,本文将详细介绍如何在 CentOS 上设置 HTTPS。
准备工作
在开始设置 HTTPS 之前,你需要以下准备工作:
- 一台安装了 CentOS 的服务器。
- 一个有效的 SSL/TLS 证书,你可以通过购买证书或使用免费的 Let's Encrypt 证书来获取。
- root 权限的访问权限。
安装必要的软件
你需要安装 Apache 或 Nginx 服务器,以及用于处理 SSL/TLS 的软件包。
Apache 服务器
# 安装 Apache 服务器 sudo yum install httpd # 启动 Apache 服务 sudo systemctl start httpd # 设置 Apache 服务开机自启 sudo systemctl enable httpd
Nginx 服务器
# 安装 Nginx 服务器 sudo yum install nginx # 启动 Nginx 服务 sudo systemctl start nginx # 设置 Nginx 服务开机自启 sudo systemctl enable nginx
获取 SSL/TLS 证书
你可以通过 Let's Encrypt 获取免费的 SSL/TLS 证书,以下是在 Nginx 上使用 Certbot 获取证书的步骤。
使用 Certbot 获取 Let's Encrypt 证书
# 安装 Certbot sudo yum install certbot python2-certbot-apache # 或 python3-certbot-nginx # 获取证书 sudo certbot --apache # 对于 Apache # sudo certbot --nginx # 对于 Nginx
执行上述命令后,Certbot 会自动为你获取证书,并将证书文件放置在指定的目录。

配置 HTTPS
获取证书后,你需要配置 Apache 或 Nginx 以使用 HTTPS。
配置 Apache
编辑 Apache 的配置文件,通常位于 /etc/httpd/conf/httpd.conf:
<VirtualHost *:443>
ServerAdmin webmaster@yourdomain.com
DocumentRoot /var/www/html
ServerName yourdomain.com
ServerAlias www.yourdomain.com
SSLEngine on
SSLCertificateFile /etc/letsencrypt/live/yourdomain.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/yourdomain.com/privkey.pem
SSLCertificateChainFile /etc/letsencrypt/live/yourdomain.com/chain.pem
<Directory />
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost> 配置 Nginx
编辑 Nginx 的配置文件,通常位于 /etc/nginx/nginx.conf:
server {
listen 443 ssl;
server_name yourdomain.com www.yourdomain.com;
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
ssl_session_tickets off;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256...';
ssl_prefer_server_ciphers on;
location / {
root /var/www/html;
index index.html index.htm;
}
} 重启服务
配置完成后,重启 Apache 或 Nginx 服务以应用更改。
# 对于 Apache sudo systemctl restart httpd # 对于 Nginx sudo systemctl restart nginx
FAQs
Q1:如何检查 HTTPS 是否设置成功?

A1:你可以使用在线工具,如 SSL Labs 的 SSL Server Test,来检查你的 HTTPS 配置是否正确。
Q2:如何更新 Let's Encrypt 证书?
A2:你可以使用 Certbot 的 renew 命令来更新 Let's Encrypt 证书,以下是在 Nginx 上使用 Certbot 更新证书的命令:
sudo certbot renew --nginx

