在Ubuntu上配置PHP、Nginx和Redis的完整指南如下:
sudo apt update && sudo apt upgrade -y
sudo apt install nginx -y
sudo systemctl start nginx
sudo systemctl enable nginx
http://your_server_ip
应看到Nginx欢迎页。sudo apt install software-properties-common
sudo add-apt-repository ppa:ondrej/php -y
sudo apt update
sudo apt install php8.1-fpm php8.1-cli php8.1-mysql php8.1-redis php8.1-curl php8.1-gd php8.1-mbstring -y
sudo systemctl start php8.1-fpm
sudo systemctl enable php8.1-fpm
sudo nano /etc/nginx/sites-available/default
server
块(关键部分):server {
listen 80;
root /var/www/html;
index index.php index.html;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
}
}
sudo nginx -t && sudo systemctl reload nginx
echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php
访问 http://your_server_ip/info.php
验证PHP是否正常工作。
sudo apt install redis-server -y
sudo systemctl start redis-server
sudo systemctl enable redis-server
redis-cli ping
# 应返回 "PONG"
/etc/redis/redis.conf
,取消注释并修改:requirepass your_strong_password
重启服务:
sudo systemctl restart redis-server
sudo nano /var/www/html/redis-test.php
内容如下:
<?php
$redis = new Redis();
try {
$redis->connect('127.0.0.1', 6379);
$redis->auth('your_password_if_set'); // 如果设置了密码
$redis->set('test_key', 'Hello Redis!');
echo $redis->get('test_key');
} catch (Exception $e) {
echo "Redis连接失败: " . $e->getMessage();
}
?>
http://your_server_ip/redis-test.php
应显示 "Hello Redis!"。sudo rm /var/www/html/info.php /var/www/html/redis-test.php
sudo ufw allow 'Nginx Full'
sudo ufw enable
sudo apt update && sudo apt upgrade -y
502 Bad Gateway
检查PHP-FPM是否运行:sudo systemctl status php8.1-fpm
确认Nginx配置中的socket路径正确。
Redis连接失败
检查Redis是否监听本地:sudo netstat -tulnp | grep 6379
如果使用云服务器,需在redis.conf
中绑定0.0.0.0
并设置密码。
PHP扩展未加载
运行php -m
查看已加载模块,用sudo apt install php8.1-{extension}
安装缺失扩展。
按照以上步骤,您已成功在Ubuntu上配置了Nginx+PHP+Redis环境。如需更高版本组件,可调整PPA源或版本号。