Ubuntu 22.04 安装 PHP(示例 PHP 8.1)
安装 PHP-FPM
sudo apt install php-fpm -y
或一起安装常用扩展
sudo apt install php-fpm php-cli php-common php-mysql php-curl php-gd php-mbstring php-xml php-zip -y
(22.04 默认是 PHP 8.1)
启动并设置开机自启
sudo systemctl enable php8.1-fpm sudo systemctl start php8.1-fpm
确认状态:
systemctl status php8.1-fpm
修改 Nginx 默认站点配置
sudo nano /etc/nginx/sites-available/default
找到或添加这段(很关键):
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
}
完整:
server {
listen 80;
server_name _;
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.1-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
确保 root 路径正确,例如:
root /var/www/html;
测试 PHP 是否生效
sudo nano /var/www/html/info.php
内容:
<?php phpinfo(); ?>
浏览器访问:
http://IP/info.php
看到 PHP 信息页说明成功 ✅
测试完记得删掉info.php
sudo rm /var/www/html/info.php