插件窝 干货文章 Ubuntu如何配置php、nginx和redis

Ubuntu如何配置php、nginx和redis

Redis PHP sudo Nginx 880    来源:    2025-04-24

在Ubuntu上配置PHP、Nginx和Redis的完整指南如下:


一、系统更新

sudo apt update && sudo apt upgrade -y

二、安装Nginx

  1. 安装:
sudo apt install nginx -y
  1. 启动并设置开机自启:
sudo systemctl start nginx
sudo systemctl enable nginx
  1. 验证: 访问 http://your_server_ip 应看到Nginx欢迎页。

三、安装PHP(以PHP 8.1为例)

  1. 添加PHP仓库:
sudo apt install software-properties-common
sudo add-apt-repository ppa:ondrej/php -y
sudo apt update
  1. 安装PHP及常用扩展:
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
  1. 启动PHP-FPM:
sudo systemctl start php8.1-fpm
sudo systemctl enable php8.1-fpm

四、配置Nginx处理PHP

  1. 编辑默认站点配置:
sudo nano /etc/nginx/sites-available/default
  1. 修改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;
    }
}
  1. 测试并重载Nginx:
sudo nginx -t && sudo systemctl reload nginx
  1. 创建测试文件:
echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php

访问 http://your_server_ip/info.php 验证PHP是否正常工作。


五、安装Redis

  1. 安装Redis服务器:
sudo apt install redis-server -y
  1. 启动并设置开机自启:
sudo systemctl start redis-server
sudo systemctl enable redis-server
  1. 验证Redis:
redis-cli ping
# 应返回 "PONG"
  1. (可选)配置Redis密码: 编辑 /etc/redis/redis.conf,取消注释并修改:
requirepass your_strong_password

重启服务:

sudo systemctl restart redis-server

六、PHP连接Redis测试

  1. 创建测试脚本:
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();
}
?>
  1. 访问 http://your_server_ip/redis-test.php 应显示 "Hello Redis!"。

七、安全加固建议

  1. 删除测试文件:
sudo rm /var/www/html/info.php /var/www/html/redis-test.php
  1. 配置防火墙:
sudo ufw allow 'Nginx Full'
sudo ufw enable
  1. 定期更新软件:
sudo apt update && sudo apt upgrade -y

常见问题解决

  1. 502 Bad Gateway
    检查PHP-FPM是否运行:sudo systemctl status php8.1-fpm
    确认Nginx配置中的socket路径正确。

  2. Redis连接失败
    检查Redis是否监听本地:sudo netstat -tulnp | grep 6379
    如果使用云服务器,需在redis.conf中绑定0.0.0.0并设置密码。

  3. PHP扩展未加载
    运行php -m查看已加载模块,用sudo apt install php8.1-{extension}安装缺失扩展。


按照以上步骤,您已成功在Ubuntu上配置了Nginx+PHP+Redis环境。如需更高版本组件,可调整PPA源或版本号。