温馨提示×

Ubuntu下如何配置SSL证书

小樊
37
2025-11-15 09:28:33
栏目: 云计算

Ubuntu 下配置 SSL 证书

一 准备与前提

  • 准备内容:一个可解析到服务器的域名(如:example.com),服务器开放TCP 80/443端口,域名已正确解析到服务器 IP。
  • 安装基础工具:
    • 安装 OpenSSL:sudo apt update && sudo apt install openssl
    • 安装 Web 服务器(二选一或两者皆有):
      • Nginx:sudo apt install nginx
      • Apache:sudo apt install apache2
  • 防火墙放行(如使用 UFW):
    • Nginx:sudo ufw allow 'Nginx Full'
    • Apache:sudo ufw allow 'Apache Full'
      以上准备完成后即可进入证书获取与部署阶段。

二 获取证书

  • 方式 A 自签名证书(仅测试环境)
    • 生成私钥与证书(有效期365 天):
      • 生成私钥:openssl genrsa -out mydomain.key 2048
      • 生成自签名证书:openssl x509 -req -days 365 -in mydomain.csr -signkey mydomain.key -out mydomain.crt
    • 说明:自签名证书在浏览器会提示不受信任,适合内网或开发测试。
  • 方式 B Let’s Encrypt 免费证书(生产推荐)
    • 安装 Certbot:
      • Nginx:sudo apt install certbot python3-certbot-nginx
      • Apache:sudo apt install certbot python3-certbot-apache
    • 获取并自动配置:
      • Nginx:sudo certbot --nginx -d example.com -d www.example.com
      • Apache:sudo certbot --apache -d example.com -d www.example.com
    • 证书路径通常为:/etc/letsencrypt/live/example.com/fullchain.pem(证书链)与**/etc/letsencrypt/live/example.com/privkey.pem**(私钥)。
      Let’s Encrypt 证书有效期为90 天,建议使用 Certbot 自动续期。

三 在 Nginx 中部署

  • 基本配置示例(/etc/nginx/sites-available/your-domain.conf):
    • 监听 443 ssl 并启用 HTTP/2
      • listen 443 ssl http2;
      • listen [::]:443 ssl http2;
    • 指定证书与私钥:
      • ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
      • ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    • 协议与加密套件:
      • ssl_protocols TLSv1.2 TLSv1.3;
      • ssl_prefer_server_ciphers on;
      • ssl_ciphers HIGH:!aNULL:!MD5;
    • HTTP 到 HTTPS 重定向(80 端口):
      • server { listen 80; server_name example.com www.example.com; return 301 https://$host$request_uri; }
  • 检查并重载:
    • 语法检查:sudo nginx -t
    • 生效:sudo systemctl reload nginx
      以上配置可确保启用现代 TLS 并强制全站 HTTPS。

四 在 Apache 中部署

  • 启用模块与站点:
    • 启用 SSL 模块:sudo a2enmod ssl
    • 启用默认 SSL 站点:sudo a2ensite default-ssl.conf(或自定义 SSL 配置)
  • 配置证书路径(/etc/apache2/sites-available/default-ssl.conf 或自定义 VirtualHost):
    • SSLEngine on
    • SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
    • SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
  • HTTP 到 HTTPS 重定向(/etc/apache2/sites-available/000-default.conf):
    • <VirtualHost *:80> ... Redirect permanent / https://example.com/ </VirtualHost>
  • 检查并重载:
    • 语法检查:sudo apache2ctl configtest
    • 生效:sudo systemctl restart apache2
      以上步骤完成后,Apache 将同时支持端口 80/443 并自动跳转至 HTTPS

五 验证与运维

  • 连通性与证书查看:
    • 命令行测试:openssl s_client -connect example.com:443
    • 浏览器访问:检查地址栏锁标识与证书颁发者。
  • 安全评分与优化:
    • 使用 SSL Labs SSL Server Test 检测配置强度,按需开启 HSTSOCSP Stapling 等增强项。
  • 自动续期与定时任务:
    • Let’s Encrypt 证书有效期 90 天,Certbot 默认注册 certbot.timer 自动续期:
      • 启用与启动:sudo systemctl enable --now certbot.timer
      • 测试续期:sudo certbot renew --dry-run
        定期验证与续期可确保长期稳定与安全的 HTTPS 服务。

0