温馨提示×

debian lamp怎样配置ssl

小樊
38
2026-10-22 08:01:37
栏目: 云计算

在 Debian 上配置 LAMP(Linux + Apache + MySQL/MariaDB + PHP) 并使用 SSL(HTTPS),通常有两种常见方式:

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

下面分别说明。


一、准备工作

1. 更新系统

sudo apt update
sudo apt upgrade -y

2. 安装 LAMP(如未安装)

sudo apt install apache2 mariadb-server php libapache2-mod-php php-mysql -y

3. 确保域名解析

  • 你的域名(如 example.com)已解析到服务器 IP
  • 80 和 443 端口已开放

二、使用 Let’s Encrypt 配置 SSL(推荐)

1. 安装 Certbot

sudo apt install certbot python3-certbot-apache -y

2. 获取并自动配置 SSL

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

按提示输入邮箱、同意条款
推荐选择 Redirect(强制 HTTPS)

3. 验证自动续期

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

2. 配置 Apache SSL

sudo a2enmod ssl
sudo a2ensite default-ssl

编辑配置文件:

sudo nano /etc/apache2/sites-available/default-ssl.conf

修改以下两行:

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

3. 重启 Apache

sudo systemctl restart apache2

访问:

https://你的服务器IP

(浏览器会提示不安全,属正常)


四、Apache 虚拟主机示例(HTTPS)

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

    SSLEngine on
    SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem

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

启用站点:

sudo a2ensite example.conf
sudo systemctl reload apache2

五、常见问题

1. 网站无法访问 HTTPS

  • 检查防火墙:ufw allow 443
  • 检查 Apache 是否监听 443

2. 强制 HTTP 跳转 HTTPS

在 .htaccess 或 Apache 配置中添加:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

如果你需要:

  • 多域名 / 通配符证书
  • Nginx + LAMP
  • Debian 12 特定版本配置

可以告诉我你的具体环境,我可以进一步细化。

0 踩