为了使用 Nginx 搭建 PHP 环境,你需要执行以下步骤:
安装 Nginx 和 PHP-FPM。
配置 Nginx 以使其能够处理 PHP 文件,并将其传递给 PHP-FPM。
配置 PHP-FPM。
以下是在 Ubuntu 系统上进行的示例安装和配置步骤:
安装 Nginx 和 PHP-FPM:
sudo apt update
sudo apt install nginx php-fpm
配置 Nginx 虚拟主机以处理 PHP 请求。编辑 Nginx 配置文件:
sudo nano /etc/nginx/sites-available/default
在该文件中,确保有一个 server 块,并在 server 块内添加以下内容:
server {
listen 80;
server_name localhost;
root /var/www/html;
index index.php index.html index.htm index.nginx-debian.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;
}
}
保存并关闭配置文件,然后重启 Nginx:
sudo systemctl restart nginx
确保 PHP-FPM 正在运行,并在需要时启动它:
sudo systemctl status php7.4-fpm
sudo systemctl start php7.4-fpm
现在,你应该有一个运行中的 Nginx 服务器,它可以处理 PHP 文件请求,并将这些请求传递给 PHP-FPM 进程管理器。
创建一个简单的 PHP 文件以测试:
echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php