在 CentOS 上让 PHP 项目支持 HTTPS,本质上是在 Web 服务器(Apache / Nginx) 上配置 SSL 证书,PHP 本身不需要特殊“开启 HTTPS”,只要运行在 HTTPS 环境下即可。
下面分别说明 Apache 和 Nginx 的常见配置方式。
通常有两类:
yum install -y certbot
certbot --apache
certbot --nginx
证书位置一般:
/etc/letsencrypt/live/域名/
├── fullchain.pem
└── privkey.pem
yum install -y mod_ssl
编辑:
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>
systemctl restart httpd
yum install -y nginx php-fpm
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;
}
}
systemctl restart nginx
systemctl restart php-fpm
<VirtualHost *:80>
ServerName www.example.com
Redirect permanent / https://www.example.com/
</VirtualHost>
server {
listen 80;
server_name www.example.com;
return 301 https://$host$request_uri;
}
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
如果你告诉我:
我可以给你精确配置文件示例。