在CentOS上配置LNMP(Linux, Nginx, MySQL/MariaDB, PHP)环境中的数据库连接,通常涉及以下几个步骤:
安装数据库服务器:
yum install mysql-server
命令安装。yum install mariadb-server mariadb
命令安装。启动并启用数据库服务:
systemctl start mysqld # 对于MySQL
systemctl enable mysqld # 对于MySQL
systemctl start mariadb # 对于MariaDB
systemctl enable mariadb # 对于MariaDB
安全配置数据库:
mysql_secure_installation
命令来设置root密码,禁止远程root登录,删除匿名用户等。创建数据库和用户:
mysql
命令行工具或者phpMyAdmin来创建数据库和用户,并授予相应的权限。CREATE DATABASE your_database_name;
CREATE USER 'your_username'@'localhost' IDENTIFIED BY 'your_password';
GRANT ALL PRIVILEGES ON your_database_name.* TO 'your_username'@'localhost';
FLUSH PRIVILEGES;
配置PHP连接数据库:
/etc/php.ini
或者通过php-fpm
的池配置文件),确保PDO
和相应的数据库扩展(如pdo_mysql
或pdo_mariadb
)已启用。<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// 设置PDO错误模式为异常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
配置Nginx:
/etc/nginx/conf.d/
或/etc/nginx/sites-available/
),设置正确的root目录和location块。server {
listen 80;
server_name your_domain.com www.your_domain.com;
root /path/to/your/webroot;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock; # 或者使用127.0.0.1:9000
}
location ~ /\.ht {
deny all;
}
}
重启服务:
systemctl restart nginx
systemctl restart php-fpm # 如果使用的是PHP-FPM
确保按照实际情况替换上述命令中的your_database_name
、your_username
、your_password
和your_domain.com
等占位符。完成这些步骤后,你的CentOS LNMP环境应该已经配置好了数据库连接。