温馨提示×

debian nginx如何配置php

小樊
43
2026-10-03 14:20:47
栏目: 编程语言

在 Debian 上让 Nginx 支持 PHP,通常是通过 PHP-FPM(FastCGI) 来实现的。下面是从零开始的标准配置步骤。


一、安装 Nginx 和 PHP

1. 更新系统

sudo apt update
sudo apt upgrade -y

2. 安装 Nginx

sudo apt install nginx -y

3. 安装 PHP 和 PHP-FPM

以 PHP 8.2 为例(Debian 12 默认版本可能不同):

sudo apt install php-fpm php-cli php-mysql -y

如果你需要其他扩展:

sudo apt install php-curl php-gd php-mbstring php-xml

二、确认 PHP-FPM 运行状态

查看 PHP-FPM 服务名(可能不同):

systemctl status php8.2-fpm

启动并设置开机自启:

sudo systemctl enable php8.2-fpm
sudo systemctl start php8.2-fpm

PHP-FPM 默认监听:

unix:/run/php/php8.2-fpm.sock

三、配置 Nginx 支持 PHP

1. 编辑站点配置

以默认站点为例:

sudo nano /etc/nginx/sites-available/default

2. 修改 server 块

示例完整配置(重点看 location ~ \.php$):

server {
    listen 80;
    server_name example.com;  # 或 _

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

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

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;
    }

    location ~ /\.ht {
        deny all;
    }
}

四、测试 PHP 是否生效

1. 创建测试文件

echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php

2. 检查 Nginx 配置

sudo nginx -t

3. 重载 Nginx

sudo systemctl reload nginx

4. 浏览器访问

http://服务器IP/info.php

看到 PHP 信息页即配置成功。


五、常见问题排查

1. 502 Bad Gateway

原因通常是:

  • PHP-FPM 未启动
  • fastcgi_pass 路径错误

检查:

ls /run/php/

2. 下载 PHP 文件而不是执行

说明 Nginx 没识别 .php

  • 确认 location ~ \.php$ 存在
  • 已 reload nginx

3. 权限问题

sudo chown -R www-data:www-data /var/www/html

六、安全建议(生产环境)

  • 删除 info.php
  • 使用 HTTPS(Let’s Encrypt)
  • 限制 PHP 执行目录

如果你告诉我:

  • Debian 版本(11 / 12)
  • PHP 版本需求
  • 是否用虚拟主机 / 子目录

我可以给你更精确的配置文件。

0 踩