0x00前言
Nginx: nginx/1.20.1
MariaDB: 5.5.68-MariaDB
PHP: PHP 7.4.33
0x01脚本
#!/bin/bash
# 确保以 root 用户身份运行
if [ "$(id -u)" -ne 0 ]; then
echo "请使用 root 用户或 sudo 权限运行该脚本"
exit 1
fi
# 开启错误处理
set -e
echo "准备更换 YUM 源..."
# 备份旧的 YUM 源
mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup 2>/dev/null || true
# 更换为阿里云镜像源
curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
yum clean all
yum makecache fast
echo "系统更新中..."
yum -y update
echo "安装基础工具..."
yum -y install wget vim net-tools unzip epel-release
echo "安装 Nginx..."
yum -y install nginx
systemctl start nginx
systemctl enable nginx
systemctl status nginx
echo "配置防火墙..."
systemctl start firewalld
systemctl enable firewalld
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload
echo "安装 MariaDB 数据库..."
yum -y install mariadb-server mariadb
systemctl start mariadb
systemctl enable mariadb
systemctl status mariadb
echo "安装 PHP 7.4..."
yum -y install https://rpms.remirepo.net/enterprise/remi-release-7.rpm
yum -y install yum-utils
yum-config-manager --enable remi-php74
yum -y install php php-fpm php-mysqlnd php-cli php-gd php-mbstring php-xml php-opcache php-json php-curl
echo "配置 PHP-FPM..."
sed -i 's/user = apache/user = nginx/' /etc/php-fpm.d/www.conf
sed -i 's/group = apache/group = nginx/' /etc/php-fpm.d/www.conf
sed -i 's/;listen.owner = nobody/listen.owner = nginx/' /etc/php-fpm.d/www.conf
sed -i 's/;listen.group = nobody/listen.group = nginx/' /etc/php-fpm.d/www.conf
systemctl enable php-fpm
systemctl start php-fpm
systemctl status php-fpm
echo "配置 Nginx..."
cat > /etc/nginx/nginx.conf <<EOF
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
include /etc/nginx/conf.d/*.conf;
}
EOF
cat > /etc/nginx/conf.d/default.conf <<EOF
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.php index.html index.htm;
location / {
try_files \$uri \$uri/ =404;
}
location ~ \.php$ {
root /usr/share/nginx/html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
include fastcgi_params;
}
}
EOF
echo "检查 Nginx 配置..."
nginx -t
echo "设置文件权限..."
chown -R nginx:nginx /usr/share/nginx/html
echo "重启 Nginx..."
systemctl restart nginx
echo "LNMP 环境安装完成!"
echo "Nginx: $(nginx -v 2>&1)"
echo "MariaDB: $(mysql --version)"
echo "PHP: $(php -v | head -n 1)"
# 创建 PHP 测试页面
echo "<?php phpinfo(); ?>" > /usr/share/nginx/html/phpinfo.php
IP=$(hostname -I | awk '{print $1}')
echo "已创建测试页面:http://$IP/phpinfo.php"