在Debian系统上配置LNMP(Linux, Nginx, MySQL/MariaDB, PHP)环境并设置数据库,可以按照以下步骤进行:
首先,更新包列表并安装Nginx:
sudo apt update
sudo apt install nginx
启动Nginx并设置开机自启动:
sudo systemctl start nginx
sudo systemctl enable nginx
接下来,安装MySQL或MariaDB。这里以MariaDB为例:
sudo apt update
sudo apt install mariadb-server mariadb-client
启动MariaDB并设置开机自启动:
sudo systemctl start mariadb
sudo systemctl enable mariadb
运行安全脚本以提高安全性:
sudo mysql_secure_installation
按照提示设置root密码,删除匿名用户,禁止root远程登录,删除测试数据库等。
安装PHP及其常用扩展:
sudo apt update
sudo apt install php-fpm php-mysql
启动PHP-FPM并设置开机自启动:
sudo systemctl start php7.4-fpm
sudo systemctl enable php7.4-fpm
配置Nginx以使用PHP-FPM处理PHP文件。编辑Nginx默认站点配置文件:
sudo nano /etc/nginx/sites-available/default
在server
块中添加以下内容:
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
index index.php index.html index.htm index.nginx-debian.html;
server_name _;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
保存并退出编辑器,然后测试Nginx配置并重启服务:
sudo nginx -t
sudo systemctl restart nginx
登录到MariaDB并创建数据库和用户:
sudo mysql -u root -p
在MySQL提示符下执行以下SQL命令:
CREATE DATABASE mydatabase;
CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypassword';
GRANT ALL PRIVILEGES ON mydatabase.* TO 'myuser'@'localhost';
FLUSH PRIVILEGES;
EXIT;
创建一个PHP文件来测试数据库连接。例如,创建一个名为info.php
的文件:
sudo nano /var/www/html/info.php
添加以下内容:
<?php
$servername = "localhost";
$username = "myuser";
$password = "mypassword";
$dbname = "mydatabase";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$conn->close();
?>
保存并退出编辑器,然后在浏览器中访问http://your_server_ip/info.php
,如果看到“Connected successfully”消息,说明数据库连接配置成功。
通过以上步骤,你就可以在Debian系统上成功配置LNMP环境并设置数据库。