温馨提示×

ubuntu apache2怎样配置https

小樊
38
2026-10-25 17:04:39
栏目: 智能运维

在 Ubuntu 上通过 Apache2 配置 HTTPS,通常有两种常见方式:

  1. 使用 Let’s Encrypt(推荐,免费)
  2. 使用自签名证书(测试用)

下面分别说明。


一、使用 Let’s Encrypt 免费证书(生产环境推荐)

1. 安装 Apache 和 Certbot

sudo apt update
sudo apt install apache2
sudo apt install certbot python3-certbot-apache

2. 确保域名解析正确

确保你的域名(如 example.com)已解析到服务器公网 IP。

3. 启用必要的 Apache 模块

sudo a2enmod ssl
sudo a2enmod rewrite
sudo systemctl restart apache2

4. 自动申请并配置 HTTPS

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

按提示选择:

  • 是否重定向 HTTP → HTTPS(建议选 2)

5. 验证自动续期

sudo certbot renew --dry-run

✅ 配置完成后,访问 https://example.com 即可。


二、使用自签名证书(仅测试)

1. 生成证书

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

按提示填写信息(Common Name 填你的域名或 IP)。

2. 创建 Apache HTTPS 站点配置

sudo nano /etc/apache2/sites-available/ssl.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>

3. 启用模块和站点

sudo a2enmod ssl
sudo a2ensite ssl.conf
sudo systemctl restart apache2

三、强制 HTTP 跳转到 HTTPS(可选)

在站点配置中添加:

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

然后:

sudo systemctl reload apache2

四、常见问题排查

  • 防火墙:确保 80 / 443 端口开放
    sudo ufw allow 'Apache Full'
    
  • 证书不生效:检查域名解析和 Apache 配置是否启用
  • 浏览器警告:自签名证书会提示不安全,属正常现象

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

  • Ubuntu 版本
  • 是否有域名
  • 是否用在公网或内网

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

0 踩