利用LNMP(Linux, Nginx, MySQL, PHP)实现动态网站的过程可以分为以下几个步骤:
Nginx是一个高性能的HTTP和反向代理服务器,也可以作为IMAP/POP3/SMTP代理服务器。
在大多数Linux发行版上,可以使用包管理器来安装Nginx。例如,在Ubuntu上:
sudo apt update
sudo apt install nginx
编辑Nginx的默认配置文件 /etc/nginx/sites-available/default
或创建一个新的配置文件。
server {
listen 80;
server_name example.com www.example.com;
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:/var/run/php/php7.4-fpm.sock; # 根据你的PHP版本调整
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
MySQL是一个流行的关系型数据库管理系统。
在Ubuntu上:
sudo apt update
sudo apt install mysql-server
运行安全脚本以提高安全性:
sudo mysql_secure_installation
PHP是一种广泛使用的服务器端脚本语言。
在Ubuntu上:
sudo apt update
sudo apt install php-fpm php-mysql
编辑PHP-FPM配置文件 /etc/php/7.4/fpm/pool.d/www.conf
或根据你的PHP版本调整路径。
listen = /var/run/php/php7.4-fpm.sock
listen.owner = www-data
listen.group = www-data
user = www-data
group = www-data
重启PHP-FPM服务:
sudo systemctl restart php7.4-fpm
在 /var/www/html
目录下创建你的网站文件和目录。
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 输出数据
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
登录到MySQL并创建数据库和表:
CREATE DATABASE your_database;
USE your_database;
CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL
);
INSERT INTO users (name) VALUES ('John Doe'), ('Jane Smith');
在浏览器中访问你的服务器地址(例如 http://example.com
),你应该能够看到从数据库中检索的数据。
通过以上步骤,你可以利用LNMP堆栈成功搭建一个动态网站。