温馨提示×

Ubuntu中PHP与Nginx如何协同工作

小樊
38
2025-12-06 14:38:46
栏目: 编程语言

Ubuntu 中 Nginx 与 PHP 的协同机制与快速搭建

工作原理

  • Nginx 负责接收 HTTP/HTTPS 请求并进行静态资源处理、反向代理与负载均衡。
  • 当请求命中 .php 文件时,Nginx 通过 FastCGI 协议将请求转发给 PHP-FPM(FastCGI Process Manager)
  • PHP-FPM 解析并执行脚本,将结果通过 FastCGI 返回给 Nginx,再由 Nginx 回传给浏览器。
  • 两者通常通过 **Unix 套接字(如:/var/run/php/php8.1-fpm.sock)**或 **TCP 端口(如:127.0.0.1:9000)**通信;生产环境更推荐 Unix 套接字以获得更好的性能与更低开销。

快速搭建步骤

  • 安装组件(以 Ubuntu 20.04/22.04 为例,选择所需 PHP 版本,如 8.1):
    • 更新索引并安装:
      sudo apt update && sudo apt install -y nginx php8.1-fpm
    • 若默认源不含所需版本,可添加 Ondřej Surý 的 PPA 后再安装:
      sudo apt install -y software-properties-common
      sudo add-apt-repository -y ppa:ondrej/php
      sudo apt update
      sudo apt install -y php8.1 php8.1-fpm
  • 启动并设置开机自启:
    sudo systemctl start nginx php8.1-fpm
    sudo systemctl enable nginx php8.1-fpm
  • 验证服务状态:
    sudo systemctl status nginx
    sudo systemctl status php8.1-fpm
  • 创建测试文件:
    echo “” | sudo tee /var/www/html/info.php
  • 访问测试:打开浏览器访问 http://服务器IP/info.php,看到 PHP 信息页即表示基础环境可用。

Nginx 与 PHP-FPM 集成配置

  • 站点配置示例(/etc/nginx/sites-available/your_domain.conf):
    server {
    listen 80;
    server_name your_domain.com www.your_domain.com;
    root /var/www/your_domain.com/html;
    index index.php index.html;
    location / {
    try_files $uri $uri/ =404;
    }
    location ~ .php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; # 与已安装版本保持一致
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
    }
    location ~ /.ht { deny all; }
    }
  • 启用站点并生效:
    sudo ln -s /etc/nginx/sites-available/your_domain.conf /etc/nginx/sites-enabled/
    sudo nginx -t && sudo systemctl reload nginx
  • 说明:
    • 使用 Unix 套接字时,需确保 Nginx 与 PHP-FPM 对套接字文件具有一致的访问权限(常见运行用户为 www-data)。
    • 也可改用 TCP 方式:将 fastcgi_pass 改为 127.0.0.1:9000,并在 PHP-FPM 的 /etc/php/8.1/fpm/pool.d/www.conf 中设置对应的 listen = 127.0.0.1:9000

常见问题排查

  • 出现 空白页502 Bad Gateway
    • 查看 Nginx 错误日志(如:/var/log/nginx/error.log)与 PHP-FPM 日志(如:/var/log/php8.1-fpm.log)。
    • 核对 fastcgi_pass 地址与 PHP-FPM 的 listen 是否一致(套接字路径或端口)。
    • 检查 网站目录权限运行用户(常见为 www-data),必要时调整所有者与权限。
    • 确认 Nginx 与 PHP-FPM 服务处于运行状态。
  • 其他建议:
    • 修改配置后先执行 sudo nginx -t 校验语法,再 reload/restart
    • 生产环境建议禁用或删除 /var/www/html/info.php 等敏感测试文件。

安全与进阶建议

  • 启用 HTTPS:使用 Certbot 自动申请与续期 Let’s Encrypt 证书,或手动配置 TLS,确保 443 端口开放与证书自动续期。
  • 防火墙放行:如使用 UFW,建议允许 Nginx Full(包含 80/443):sudo ufw allow ‘Nginx Full’。
  • 文件与目录权限:网站目录建议归属 www-data:www-data,权限 755(文件 644),避免权限过宽导致安全风险。
  • 版本与扩展:根据应用需求安装所需 PHP 扩展(如 php8.1-mysql、php8.1-gd、php8.1-mbstring、php8.1-curl、php8.1-xml、php8.1-zip 等),并保持系统与软件包 及时更新

0