温馨提示×

ubuntu php如何开启ssl

小樊
44
2026-09-10 08:54:16
栏目: 云计算

在 Ubuntu 上让 PHP 支持 / 开启 SSL,通常分两种场景
1️⃣ PHP 作为 Web 服务器(Apache / Nginx) 对外提供 HTTPS
2️⃣ PHP 代码里使用 SSL(如 curl https、SSL socket、mail SSL)

下面按常见情况说明。


一、先确认 PHP 是否已支持 SSL

php -m | grep ssl

或:

php -i | grep -i ssl

如果看到 openssl,说明 PHP 已支持 SSL。


二、PHP 使用 SSL(curl / openssl)

1️⃣ 安装 OpenSSL 扩展(一般已默认开启)

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

2️⃣ curl 使用 HTTPS(常见)

确保 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);

三、Apache 开启 HTTPS(PHP 网站用 SSL)

1️⃣ 启用 SSL 模块

sudo a2enmod ssl
sudo systemctl restart apache2

2️⃣ 配置 SSL 站点

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


四、Nginx + PHP 开启 SSL

1️⃣ 安装证书(Let’s Encrypt 示例)

sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d example.com

2️⃣ Nginx 配置示例

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;
    }
}

五、PHP 代码强制 SSL(可选)

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

如果你能说明:

  • Ubuntu 版本
  • PHP 版本
  • Apache 还是 Nginx
  • 是「网站 HTTPS」还是「PHP 内部 SSL 请求」

我可以给你精确配置命令

0