温馨提示×

centos php如何配置https

小樊
44
2026-09-24 02:27:10
栏目: 编程语言

在 CentOS 上让 PHP 项目支持 HTTPS,本质上是在 Web 服务器(Apache / Nginx) 上配置 SSL 证书,PHP 本身不需要特殊“开启 HTTPS”,只要运行在 HTTPS 环境下即可。

下面分别说明 Apache 和 Nginx 的常见配置方式。


一、准备 SSL 证书

通常有两类:

  1. 自签名证书(测试用)
  2. 正式证书(Let’s Encrypt / 商业证书)

1️⃣ 使用 Let’s Encrypt(推荐)

yum install -y certbot
  • Apache:
certbot --apache
  • Nginx:
certbot --nginx

证书位置一般:

/etc/letsencrypt/live/域名/
├── fullchain.pem
└── privkey.pem

二、Apache + PHP 配置 HTTPS(CentOS)

1️⃣ 安装 mod_ssl

yum install -y mod_ssl

2️⃣ 配置虚拟主机

编辑:

vi /etc/httpd/conf.d/ssl.conf

或新建:

vi /etc/httpd/conf.d/example.conf

示例:

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

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

    <Directory /var/www/html>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

3️⃣ 重启 Apache

systemctl restart httpd

三、Nginx + PHP 配置 HTTPS(CentOS)

1️⃣ 安装 Nginx + PHP-FPM

yum install -y nginx php-fpm

2️⃣ 配置 Nginx

vi /etc/nginx/conf.d/ssl.conf

示例:

server {
    listen 443 ssl;
    server_name www.example.com;

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

    ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;

    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

systemctl restart nginx
systemctl restart php-fpm

四、HTTP 强制跳转到 HTTPS(可选)

Apache

<VirtualHost *:80>
    ServerName www.example.com
    Redirect permanent / https://www.example.com/
</VirtualHost>

Nginx

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

五、PHP 中判断 HTTPS

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

六、常见问题

✅ 防火墙放行 443:

firewall-cmd --permanent --add-service=https
firewall-cmd --reload

✅ SELinux(如报错):

setsebool -P httpd_can_network_connect 1

如果你告诉我:

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

我可以给你精确配置文件示例。

0 踩