以下是在Ubuntu系统上配置PHP、Nginx和Redis的详细步骤:
sudo apt update
sudo apt upgrade -y
sudo apt install nginx -y
sudo systemctl start nginx
sudo systemctl enable nginx
验证Nginx是否运行:
sudo systemctl status nginx
访问服务器IP应能看到Nginx欢迎页。
sudo apt install software-properties-common -y
sudo add-apt-repository ppa:ondrej/php -y
sudo apt update
sudo apt install php8.1-fpm php8.1-cli php8.1-common php8.1-mysql php8.1-zip php8.1-gd php8.1-mbstring php8.1-curl php8.1-xml php8.1-bcmath -y
sudo systemctl start php8.1-fpm
sudo systemctl enable php8.1-fpm
验证PHP-FPM:
sudo systemctl status php8.1-fpm
php -v
编辑默认站点配置:
sudo nano /etc/nginx/sites-available/default
修改server部分(关键配置):
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;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
测试并重载Nginx:
sudo nginx -t
sudo systemctl reload nginx
创建测试文件:
echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php
访问 http://服务器IP/info.php
应看到PHP信息页。
sudo apt install redis-server -y
sudo systemctl start redis-server
sudo systemctl enable redis-server
验证Redis:
sudo systemctl status redis-server
redis-cli ping # 应返回 "PONG"
sudo apt install php8.1-redis -y
sudo systemctl restart php8.1-fpm
创建PHP测试文件验证Redis连接:
<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
echo "Connection to Redis successful. Server is running: " . $redis->ping();
?>
Redis安全:
sudo nano /etc/redis/redis.conf
修改:
requirepass your_strong_password
bind 127.0.0.1
protected-mode yes
重启Redis:
sudo systemctl restart redis-server
PHP安全:
编辑 /etc/php/8.1/fpm/php.ini
:
expose_php = Off
disable_functions = exec,passthru,shell_exec,system
Nginx安全: 考虑安装fail2ban:
sudo apt install fail2ban -y
sudo ufw allow 'Nginx Full'
sudo ufw allow ssh
sudo ufw enable
创建综合测试文件 /var/www/html/test.php
:
<?php
// PHP测试
echo "PHP: " . phpversion() . "<br>";
// Redis测试
$redis = new Redis();
try {
$redis->connect('127.0.0.1');
echo "Redis: Connected successfully<br>";
echo "Ping: " . $redis->ping() . "<br>";
} catch (Exception $e) {
echo "Redis Error: " . $e->getMessage();
}
// Nginx测试
echo "Server: " . $_SERVER['SERVER_SOFTWARE'];
?>
访问该文件应能看到所有组件正常工作。
502 Bad Gateway:
systemctl status php8.1-fpm
Redis连接失败:
/etc/redis/redis.conf
中的绑定设置PHP扩展未加载:
php -m
查看已加载模块/etc/php/8.1/fpm/conf.d
目录是否有redis.ini按照以上步骤操作后,您将在Ubuntu系统上获得一个完整的PHP+Nginx+Redis运行环境。根据实际需求,您可能需要调整配置参数或安装额外的PHP扩展。