1. 安装 Nginx 和 PHP 7.4
首先,需要在安装 Nginx 和 PHP 7.4(包括 PHP-FPM)
sudo apt update
sudo apt install nginx
sudo apt install php7.4 php7.4-fpm
确保 PHP-FPM 服务已启动:
sudo systemctl start php7.4-fpm
sudo systemctl enable php7.4-fpm
2. 配置 PHP-FPM
PHP-FPM 的默认配置通常足够用,但根据需要修改/etc/php/7.4/fpm/pool.d/www.conf 文件。
需要确认其中的 listen 参数设置为 PHP-FPM 与 Nginx 通信的方式,一般为 Unix socket 或 TCP/IP 地址。
例如,使用 Unix socket:
listen = /run/php/php7.4-fpm.sock
或者使用 TCP/IP:
listen = 127.0.0.1:9000
3. 配置 Nginx
编辑或创建一个 Nginx 配置文件来设置 PHP 请求的处理。
这通常在 /etc/nginx/sites-available 下的虚拟主机配置文件中完成。
例如,创建一个新的配置文件 /etc/nginx/sites-available/example.com 并设置以下内容:
server {
listen 80;
server_name example.com www.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/php7.4-fpm.sock;
# 或者如果你使用 TCP/IP
# fastcgi_pass 127.0.0.1:9000;
}
location ~ /\.ht {
deny all;
}
}
确保将 /etc/nginx/sites-available/example.com 链接到 /etc/nginx/sites-enabled/ 目录:
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
4. 重启 Nginx
更改配置后,重启 Nginx 以应用新的配置:
sudo systemctl restart nginx
5. 测试配置
创建一个简单的 PHP 脚本来测试配置是否正确。在网站根目录创建 info.php:
<?php phpinfo(); ?>
通过浏览器访问 http://example.com/info.php,应该能看到 PHP 的信息页面。