在 CentOS 上给 PHP 项目配置 HTTPS,通常不是“PHP 本身配 HTTPS”,而是Web 服务器(Nginx 或 Apache)配置 SSL,PHP 在后面跑。下面分两种常见情况说明。
yum install epel-release -y
yum install certbot -y
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
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;
}
}
nginx -t
systemctl restart nginx
✅ 此时 PHP 已运行在 HTTPS 下
yum install mod_ssl
certbot certonly --webroot -w /var/www/html -d example.com
<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>
systemctl restart httpd
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://
如果你告诉我:
我可以直接给你可复制的完整配置文件。