LNMP 代表 Linux + Nginx + MySQL/MariaDB + PHP,是一种常见的 Web 服务器环境组合。以下是详细的搭建步骤:
# 更新系统软件包
sudo apt update && sudo apt upgrade -y # Ubuntu/Debian
sudo yum update -y # CentOS/RHEL
# 安装常用工具
sudo apt install -y wget curl git unzip # Ubuntu/Debian
sudo yum install -y wget curl git unzip # CentOS/RHEL
sudo apt install -y nginx
sudo systemctl start nginx
sudo systemctl enable nginx
sudo yum install -y epel-release
sudo yum install -y nginx
sudo systemctl start nginx
sudo systemctl enable nginx
验证安装:
curl -I 127.0.0.1
sudo apt install -y mysql-server
sudo mysql_secure_installation
sudo systemctl start mysql
sudo systemctl enable mysql
sudo yum install -y mariadb-server mariadb
sudo systemctl start mariadb
sudo systemctl enable mariadb
sudo mysql_secure_installation
sudo apt install -y software-properties-common
sudo add-apt-repository ppa:ondrej/php
sudo apt update
sudo apt install -y php7.4 php7.4-fpm php7.4-mysql php7.4-curl php7.4-gd php7.4-mbstring php7.4-xml php7.4-zip
sudo yum install -y epel-release yum-utils
sudo yum install -y http://rpms.remirepo.net/enterprise/remi-release-7.rpm
sudo yum-config-manager --enable remi-php74
sudo yum install -y php php-fpm php-mysqlnd php-curl php-gd php-mbstring php-xml php-zip
配置 PHP-FPM:
sudo systemctl start php-fpm
sudo systemctl enable php-fpm
编辑 Nginx 默认配置文件:
sudo nano /etc/nginx/sites-available/default # Ubuntu/Debian
sudo nano /etc/nginx/conf.d/default.conf # CentOS/RHEL
添加或修改 server 块:
server {
listen 80;
server_name your_domain_or_ip;
root /var/www/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf; # Ubuntu/Debian
# include fastcgi_params; # CentOS/RHEL
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
测试并重启 Nginx:
sudo nginx -t
sudo systemctl restart nginx
创建测试文件:
sudo nano /var/www/html/info.php
添加内容:
<?php phpinfo(); ?>
访问 http://your_server_ip/info.php
查看 PHP 信息页面。
sudo apt install -y phpmyadmin # Ubuntu/Debian
sudo yum install -y phpmyadmin # CentOS/RHEL
sudo apt install -y redis-server php-redis # Ubuntu/Debian
sudo yum install -y redis php-pecl-redis # CentOS/RHEL
# 调整文件权限
sudo chown -R www-data:www-data /var/www/html # Ubuntu/Debian
sudo chown -R nginx:nginx /var/www/html # CentOS/RHEL
sudo chmod -R 755 /var/www/html
# 配置防火墙
sudo ufw allow 'Nginx Full' # Ubuntu/Debian
sudo firewall-cmd --permanent --add-service=http --add-service=https # CentOS/RHEL
sudo firewall-cmd --reload
现在你已经成功搭建了 LNMP 环境,可以开始部署你的 Web 应用了!