在 Ubuntu 上让 PHP 支持 / 开启 SSL,通常分两种场景:
1️⃣ PHP 作为 Web 服务器(Apache / Nginx) 对外提供 HTTPS
2️⃣ PHP 代码里使用 SSL(如 curl https、SSL socket、mail SSL)
下面按常见情况说明。
php -m | grep ssl
或:
php -i | grep -i ssl
如果看到 openssl,说明 PHP 已支持 SSL。
sudo apt update
sudo apt install php-openssl
Ubuntu 默认 PHP 已编译 openssl,通常不需要额外安装
重启服务:
# Apache
sudo systemctl restart apache2
# Nginx + PHP-FPM
sudo systemctl restart php8.1-fpm
sudo systemctl restart nginx
确保 curl 扩展已安装:
php -m | grep curl
没有就装:
sudo apt install php-curl
sudo systemctl restart apache2 # 或 php-fpm
测试:
<?php
$ch = curl_init("https://www.baidu.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
echo curl_exec($ch);
sudo a2enmod ssl
sudo systemctl restart apache2
sudo a2ensite default-ssl
编辑:
sudo nano /etc/apache2/sites-available/default-ssl.conf
确认:
SSLEngine on
SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem
SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
重启:
sudo systemctl restart apache2
访问:https://你的IP
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d example.com
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
}
}
if (empty($_SERVER['HTTPS'])) {
header("Location: https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
exit;
}
❌ Call to undefined function openssl_*
✅ 没开 openssl 扩展
sudo phpenmod openssl
❌ curl https 报错证书问题
✅ 安装 CA 证书:
sudo apt install ca-certificates
如果你能说明:
我可以给你精确配置命令。