温馨提示×

centos php怎么配https

小樊
54
2026-09-02 18:37:16
栏目: 编程语言

在 CentOS 上给 PHP 项目配置 HTTPS,通常不是“PHP 本身配 HTTPS”,而是Web 服务器(Nginx 或 Apache)配置 SSL,PHP 在后面跑。下面分两种常见情况说明。


一、前提准备

  1. 域名已解析到服务器
  2. 服务器开放 80 / 443 端口
  3. 已安装:
    • Nginx 或 Apache
    • PHP(php-fpm)

二、使用 Let’s Encrypt 免费证书(推荐)

1. 安装 certbot

yum install epel-release -y
yum install certbot -y

三、Nginx + PHP 配置 HTTPS(最常见)

1. 申请证书

certbot certonly --webroot -w /usr/share/nginx/html -d example.com

证书位置:

/etc/letsencrypt/live/example.com/fullchain.pem
/etc/letsencrypt/live/example.com/privkey.pem

2. 修改 Nginx 配置

server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}

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;

    root /usr/share/nginx/html;
    index index.php index.html;

    location ~ \.php$ {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}

3. 重启 Nginx

nginx -t
systemctl restart nginx

✅ 此时 PHP 已运行在 HTTPS 下


四、Apache + PHP 配置 HTTPS

1. 安装模块

yum install mod_ssl

2. 申请证书(同上)

certbot certonly --webroot -w /var/www/html -d example.com

3. 配置 ssl.conf

<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

    <FilesMatch \.php$>
        SetHandler "proxy:fcgi://127.0.0.1:9000"
    </FilesMatch>
</VirtualHost>

4. 重启 Apache

systemctl restart httpd

五、PHP 中判断是否 HTTPS

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

六、自动续期(重要)

certbot renew --dry-run

加入定时任务:

crontab -e
0 3 * * * certbot renew --quiet

七、常见坑

❌ PHP 仍显示 http
→ 前端有代理(Nginx/CDN),需加:

fastcgi_param HTTPS on;

❌ 混合内容(Mixed Content)
→ 页面里 http:// 资源要改成 https://


如果你告诉我:

  • CentOS 版本(7 / 8 / Stream)
  • Web 服务(Nginx / Apache)
  • PHP 版本

我可以直接给你可复制的完整配置文件。

0 踩