插件窝 干货文章 Nginx和PHP的部署方式是什么

Nginx和PHP的部署方式是什么

PHP Nginx FastCGI 配置 71    来源:    2025-04-23

Nginx 和 PHP 的部署通常通过 FastCGI 协议(PHP-FPM)实现协作,以下是常见的部署方式及详细步骤:


一、常见部署架构

  1. Nginx 处理静态文件(HTML/CSS/JS/图片等)。
  2. PHP-FPM(FastCGI Process Manager)处理动态 PHP 请求。
  3. 通过 Unix Socket 或 TCP 端口实现 Nginx 与 PHP-FPM 的通信。

二、详细部署步骤

1. 安装必要组件

# Ubuntu/Debian
sudo apt update
sudo apt install nginx php-fpm php-cli php-mysql php-curl php-gd  # 根据需求安装其他PHP扩展

# CentOS/RHEL
sudo yum install nginx php-fpm php-mysqlnd php-common

2. 配置 PHP-FPM

  • 编辑 PHP-FPM 配置文件(通常位于 /etc/php/{version}/fpm/pool.d/www.conf): ini listen = /run/php/php-fpm.sock # 使用Unix Socket(推荐)或 listen = 127.0.0.1:9000(TCP端口) user = www-data group = www-data
  • 重启 PHP-FPM: bash sudo systemctl restart php-fpm

3. 配置 Nginx

  • 编辑 Nginx 站点配置文件(如 /etc/nginx/sites-available/example.com):

    server {
      listen 80;
      server_name example.com;
      root /var/www/html;
    
      index index.php index.html;
    
      location / {
          try_files $uri $uri/ =404;
      }
    
      location ~ \.php$ {
          include snippets/fastcgi-php.conf;  # 包含FastCGI通用配置
          fastcgi_pass unix:/run/php/php-fpm.sock;  # 与PHP-FPM的监听方式一致
          # 如果使用TCP端口,则改为:fastcgi_pass 127.0.0.1:9000;
      }
    
      location ~ /\.ht {
          deny all;
      }
    }
    
  • 测试配置并重启 Nginx: bash sudo nginx -t sudo systemctl restart nginx

4. 测试 PHP

  • 创建测试文件 /var/www/html/info.phpphp <?php phpinfo(); ?>
  • 访问 http://example.com/info.php,确认显示 PHP 信息页面。

三、其他优化配置

  1. 性能调优

    • 调整 PHP-FPM 进程池(pm.max_children, pm.start_servers)。
    • 启用 Nginx 缓存(如 fastcgi_cache)。
  2. 安全性

    • 限制 PHP 文件执行目录: nginx location ~ \.php$ { fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; fastcgi_pass unix:/run/php/php-fpm.sock; }
    • 禁用危险函数(在 php.ini 中设置 disable_functions)。
  3. HTTPS 支持
    使用 Let's Encrypt 证书配置 SSL:

    sudo apt install certbot python3-certbot-nginx
    sudo certbot --nginx -d example.com
    

四、常见问题排查

  • 502 Bad Gateway
    检查 PHP-FPM 是否运行,且 fastcgi_pass 路径/端口与 FPM 配置一致。
  • 404 Not Found
    确保 root 路径正确,且 PHP 文件权限允许 Nginx 读取。
  • PHP 代码不执行
    确认 Nginx 配置中已正确处理 .php 文件,且 PHP-FPM 服务正常。

通过以上步骤,Nginx 和 PHP-FPM 即可协同工作,高效处理动态和静态内容。根据实际需求调整配置参数以优化性能与安全性。