温馨提示×

OpenSSL如何配置Linux服务器的SSL/TLS

小樊
76
2025-04-11 18:54:40
栏目: 云计算

配置Linux服务器的SSL/TLS使用OpenSSL涉及几个步骤。以下是一个基本的指南,帮助你在Linux服务器上设置SSL/TLS证书:

1. 安装OpenSSL

大多数Linux发行版默认已经安装了OpenSSL。如果没有安装,可以使用包管理器进行安装。

# 在Debian/Ubuntu上 sudo apt-get update sudo apt-get install openssl # 在CentOS/RHEL上 sudo yum install openssl # 在Fedora上 sudo dnf install openssl 

2. 生成自签名证书

如果你只是测试或内部使用,可以生成一个自签名证书。

# 生成私钥 openssl genpkey -algorithm RSA -out private.key -aes256 # 生成证书签名请求 (CSR) openssl req -new -key private.key -out certificate.csr # 生成自签名证书 openssl x509 -req -days 365 -in certificate.csr -signkey private.key -out certificate.crt 

在生成CSR时,你需要提供一些信息,如国家、组织名称等。

3. 获取受信任的证书

对于生产环境,你应该从受信任的证书颁发机构(CA)获取证书。以下是获取Let’s Encrypt证书的示例:

# 安装Certbot sudo apt-get install certbot # Debian/Ubuntu sudo yum install certbot # CentOS/RHEL sudo dnf install certbot # Fedora # 获取证书 sudo certbot certonly --standalone -d yourdomain.com -d www.yourdomain.com 

Certbot会自动处理证书的获取和续期。

4. 配置Web服务器

根据你使用的Web服务器(如Apache、Nginx等),配置SSL/TLS。

Apache

编辑Apache配置文件(通常是/etc/apache2/sites-available/yourdomain.com.conf),添加以下内容:

<VirtualHost *:443> 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 DocumentRoot /var/www/html <Directory /var/www/html> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> 

启用站点并重启Apache:

sudo a2ensite yourdomain.com.conf sudo systemctl restart apache2 

Nginx

编辑Nginx配置文件(通常是/etc/nginx/sites-available/yourdomain.com),添加以下内容:

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; root /var/www/html; index index.html index.htm; location / { try_files $uri $uri/ =404; } error_log /var/log/nginx/yourdomain.com.error.log; access_log /var/log/nginx/yourdomain.com.access.log; } 

启用站点并重启Nginx:

sudo ln -s /etc/nginx/sites-available/yourdomain.com /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl restart nginx 

5. 自动续期证书

Let’s Encrypt证书每90天需要续期一次。Certbot可以自动续期证书。

sudo certbot renew --dry-run sudo certbot renew 

你可以设置一个cron任务来自动执行续期:

0 0,12 * * * root certbot renew --post-hook "systemctl reload nginx" 

6. 测试配置

确保你的SSL/TLS配置正确无误。

sudo openssl s_client -connect yourdomain.com:443 -servername yourdomain.com 

检查输出以确保没有错误,并且证书信息正确。

通过以上步骤,你应该能够在Linux服务器上成功配置SSL/TLS。

0