温馨提示×

ubuntu apache怎么开启https

小樊
35
2026-10-11 01:23:36
栏目: 智能运维

在 Ubuntu 上通过 Apache 开启 HTTPS,通常分为 安装 Apache → 获取 SSL 证书 → 配置虚拟主机 → 强制跳转(可选) 几步。下面以 Ubuntu 20.04/22.04 为例说明。


一、安装 Apache(如未安装)

sudo apt update
sudo apt install apache2 -y

二、申请 SSL 证书

方式 1:使用 Let’s Encrypt(推荐,免费)

1. 安装 certbot

sudo apt install certbot python3-certbot-apache -y

2. 申请证书并自动配置

sudo certbot --apache -d example.com -d www.example.com

替换 example.com 为你自己的域名

certbot 会自动:

  • 生成证书
  • 修改 Apache 配置
  • 开启 443 端口
  • 设置 HTTP → HTTPS 跳转

方式 2:使用自签名证书(测试用)

sudo openssl req -x509 -nodes -days 365 \
  -newkey rsa:2048 \
  -keyout /etc/ssl/private/apache-selfsigned.key \
  -out /etc/ssl/certs/apache-selfsigned.crt

三、手动配置 HTTPS(如未自动配置)

1. 启用 SSL 模块

sudo a2enmod ssl
sudo systemctl restart apache2

2. 创建 HTTPS 虚拟主机

sudo nano /etc/apache2/sites-available/example.com.conf

示例配置:

<VirtualHost *:443>
    ServerName example.com
    DocumentRoot /var/www/html

    SSLEngine on
    SSLCertificateFile /etc/ssl/certs/apache-selfsigned.crt
    SSLCertificateKeyFile /etc/ssl/private/apache-selfsigned.key

    <Directory /var/www/html>
        AllowOverride All
    </Directory>
</VirtualHost>

启用站点:

sudo a2ensite example.com.conf
sudo systemctl reload apache2

四、HTTP 强制跳转 HTTPS(推荐)

编辑 80 端口配置:

<VirtualHost *:80>
    ServerName example.com
    Redirect permanent / https://example.com/
</VirtualHost>

或在使用 certbot 时选择:

2: Redirect - Make all requests redirect to secure HTTPS access

五、防火墙放行 HTTPS

sudo ufw allow 'Apache Full'

六、测试

浏览器访问:

https://example.com

七、证书自动续期(Let’s Encrypt)

sudo certbot renew --dry-run

如果你愿意,可以告诉我:

  • Ubuntu 版本
  • 是否已有域名
  • 是否用 Docker / 云服务器

我可以给你更精确的配置示例。

0 踩