ubuntu

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

小樊
34
2025-05-11 22:25:56
栏目: 编程语言

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

  1. 安装SSL证书: 你可以使用Let’s Encrypt免费获取SSL证书。首先,确保你已经安装了Certbot和Nginx(或Apache)。

    sudo apt update
    sudo apt install certbot python3-certbot-nginx
    

    如果你选择使用Apache,可以安装python3-certbot-apache

  2. 获取并安装SSL证书: 使用Certbot获取并安装SSL证书。假设你选择使用Nginx:

    sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
    

    Certbot会自动配置Nginx以使用SSL证书,并重定向HTTP流量到HTTPS。

  3. 配置PHP-FPM: PHP-FPM通常与Nginx或Apache一起使用。确保你的PHP-FPM配置正确。

    编辑PHP-FPM配置文件:

    sudo nano /etc/php/7.4/fpm/pool.d/www.conf
    

    确保以下行没有被注释掉:

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

    如果你使用的是TCP/IP而不是Unix套接字,可以改为:

    listen = 127.0.0.1:9000
    
  4. 配置Nginx: 编辑Nginx服务器块配置文件:

    sudo nano /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; # 或者使用127.0.0.1:9000
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
        }
    
        location / {
            try_files $uri $uri/ =404;
        }
    }
    

    确保将yourdomain.com替换为你的实际域名。

  5. 重启服务: 重启Nginx和PHP-FPM服务以应用更改:

    sudo systemctl restart nginx
    sudo systemctl restart php7.4-fpm
    
  6. 验证配置: 打开浏览器并访问你的域名,确保HTTPS连接正常工作,并且PHP页面能够正确解析和执行。

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

0
看了该问题的人还看了