ubuntu

如何配置Ubuntu上的PHP-FPM以支持HTTPS

小樊
41
2025-07-17 17:56:01
栏目: 编程语言

要在Ubuntu上配置PHP-FPM以支持HTTPS,你需要完成以下几个步骤:

1. 安装必要的软件

首先,确保你已经安装了Nginx和PHP-FPM。如果没有安装,可以使用以下命令进行安装:

sudo apt update
sudo apt install nginx php-fpm

2. 配置Nginx

接下来,配置Nginx以使用HTTPS。你需要一个SSL证书,可以使用Let’s Encrypt免费获取。

获取SSL证书

使用Certbot获取SSL证书:

sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

按照提示完成证书的获取和配置。

配置Nginx服务器块

编辑Nginx配置文件(通常位于/etc/nginx/sites-available/yourdomain.com),添加或修改以下内容:

server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;

    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        return 301 https://$host$request_uri;
    }
}

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

    ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    root /var/www/html;
    index index.php index.html index.htm;

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.4-fpm.sock; # 根据你的PHP版本调整
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location / {
        try_files $uri $uri/ =404;
    }
}

确保将yourdomain.com替换为你的实际域名,并根据需要调整PHP-FPM的socket路径。

3. 重启Nginx

保存配置文件后,重启Nginx以应用更改:

sudo systemctl restart nginx

4. 配置PHP-FPM

确保PHP-FPM正在运行并监听正确的socket。默认情况下,PHP-FPM会监听/run/php/php7.4-fpm.sock(根据你的PHP版本可能有所不同)。

你可以检查PHP-FPM的状态:

sudo systemctl status php7.4-fpm

如果需要,可以编辑PHP-FPM配置文件(通常位于/etc/php/7.4/fpm/pool.d/www.conf),确保以下行存在且正确:

listen = /run/php/php7.4-fpm.sock

然后重启PHP-FPM:

sudo systemctl restart php7.4-fpm

5. 测试配置

最后,访问你的域名,确保HTTPS连接正常工作,并且PHP页面能够正确处理。

通过以上步骤,你应该能够在Ubuntu上成功配置PHP-FPM以支持HTTPS。

0
看了该问题的人还看了