在 Ubuntu 上,php-fpm 本身不直接处理 SSL,SSL 通常由 Nginx 或 Apache 来终止(TLS 终结),然后以 FastCGI 方式把请求转发给 php-fpm。
下面以 Nginx + php-fpm + SSL(HTTPS) 为例说明正确配置方式。
浏览器
│ HTTPS (SSL)
▼
Nginx (处理 SSL)
│ FastCGI
▼
php-fpm (unix socket 或 tcp)
✅ SSL 配置在 Nginx,不在 php-fpm
sudo apt update
sudo apt install nginx php-fpm
查看 php 版本(示例 php8.1):
php -v
php-fpm socket 通常在:
/run/php/php8.1-fpm.sock
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d example.com
证书位置:
/etc/letsencrypt/live/example.com/fullchain.pem
/etc/letsencrypt/live/example.com/privkey.pem
编辑站点配置:
sudo nano /etc/nginx/sites-available/example.com
示例配置:
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 /var/www/html;
index index.php index.html;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
}
}
启用站点:
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
通常不需要改 SSL 相关配置
只需确认:
sudo nano /etc/php/8.1/fpm/pool.d/www.conf
确保:
listen = /run/php/php8.1-fpm.sock
或(TCP 方式):
listen = 127.0.0.1:9000
重启 php-fpm:
sudo systemctl restart php8.1-fpm
php-fpm 不支持原生 HTTPS,需:
stud / haproxy 做 SSL 终结⚠️ 复杂、不推荐
sudo openssl req -x509 -nodes -days 365 \
-newkey rsa:2048 \
-keyout /etc/ssl/private/self.key \
-out /etc/ssl/certs/self.crt
Nginx 中引用即可。
❓ php 里 $_SERVER['HTTPS'] 为空?
✅ 在 Nginx 加:
fastcgi_param HTTPS on;
❓ 强制 HTTPS?
✅ 已用 return 301 https://
如果你用的是 Apache + php-fpm 或 本地开发(Docker / 宝塔),告诉我环境,我可以给你对应配置。