温馨提示×

ubuntu php怎样配置https

小樊
38
2026-10-04 10:10:47
栏目: 编程语言

在 Ubuntu 上给 PHP 项目配置 HTTPS,通常不是直接“配置 PHP”,而是配置 Web 服务器(Apache 或 Nginx)使用 HTTPS,然后 PHP 自然就在 HTTPS 下运行了。

下面分别说明 Apache 和 Nginx 的常见做法。


一、前提条件

  1. 已安装 Web 服务器(Apache / Nginx)
  2. 已安装 PHP(如 php-fpm 或 mod_php)
  3. 拥有 SSL 证书(自签名 or 正规证书)
    • 正式环境推荐:Let’s Encrypt(免费)
    • 测试环境:自签名证书

二、使用 Let’s Encrypt(推荐,正式环境)

1. 安装 Certbot

sudo apt update
sudo apt install certbot

Apache

sudo apt install python3-certbot-apache
sudo certbot --apache

Nginx

sudo apt install python3-certbot-nginx
sudo certbot --nginx

Certbot 会自动:

  • 申请证书
  • 修改站点配置
  • 开启 443 端口
  • 配置 HTTP → HTTPS 跳转

✅ 完成后访问 https://你的域名 即可,PHP 已运行在 HTTPS 下。


三、Apache 手动配置 HTTPS(自签名示例)

1. 启用 SSL 模块

sudo a2enmod ssl
sudo systemctl restart apache2

2. 生成自签名证书

sudo mkdir -p /etc/apache2/ssl
sudo openssl req -x509 -nodes -days 365 \
  -newkey rsa:2048 \
  -keyout /etc/apache2/ssl/apache.key \
  -out /etc/apache2/ssl/apache.crt

3. 配置虚拟主机

编辑站点配置:

sudo nano /etc/apache2/sites-available/your-site.conf

示例:

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

    SSLEngine on
    SSLCertificateFile /etc/apache2/ssl/apache.crt
    SSLCertificateKeyFile /etc/apache2/ssl/apache.key

    <FilesMatch \.php$>
        SetHandler application/x-httpd-php
    </FilesMatch>
</VirtualHost>

启用站点:

sudo a2ensite your-site.conf
sudo systemctl restart apache2

四、Nginx 手动配置 HTTPS(PHP-FPM)

1. 生成证书

sudo mkdir -p /etc/nginx/ssl
sudo openssl req -x509 -nodes -days 365 \
  -newkey rsa:2048 \
  -keyout /etc/nginx/ssl/nginx.key \
  -out /etc/nginx/ssl/nginx.crt

2. 配置 Nginx

sudo nano /etc/nginx/sites-available/your-site

示例:

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate     /etc/nginx/ssl/nginx.crt;
    ssl_certificate_key /etc/nginx/ssl/nginx.key;

    root /var/www/html;
    index index.php index.html;

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.1-fpm.sock;
    }
}

启用并重启:

sudo ln -s /etc/nginx/sites-available/your-site /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx

五、PHP 本身需要注意的点

1. 判断是否是 HTTPS

if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
    echo "HTTPS";
}

2. 强制 HTTPS(PHP 层面)

if (empty($_SERVER['HTTPS'])) {
    header("Location: https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    exit;
}

六、常见问题

  • 浏览器提示不安全 → 自签名证书正常现象
  • PHP 不执行 → 检查 php-fpm / mod_php 是否启用
  • 端口未开放 → 确保 443 已放行(云服务器安全组)

如果你能告诉我:

  • 用的是 Apache 还是 Nginx
  • Ubuntu 版本
  • PHP 版本
  • 是 本地测试还是服务器正式环境

我可以给你一份完全对应的配置文件。

0 踩