下面是一个完整的Shell脚本,可以一键安装和配置Nginx服务:
#!/bin/bash
# 一键安装Nginx脚本
# 适用于CentOS/RHEL 7+ 和 Ubuntu/Debian系统
# 检查是否为root用户
if [ "$(id -u)" -ne 0 ]; then
echo "请使用root用户运行此脚本!"
exit 1
fi
# 定义颜色代码
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color
# 安装前检查系统
check_system() {
if [ -f /etc/redhat-release ]; then
SYSTEM="centos"
elif grep -Eqi "debian" /etc/issue; then
SYSTEM="debian"
elif grep -Eqi "ubuntu" /etc/issue; then
SYSTEM="ubuntu"
else
echo -e "${RED}不支持的系统!${NC}"
exit 1
fi
}
# 安装Nginx
install_nginx() {
echo -e "${YELLOW}开始安装Nginx...${NC}"
if [ "$SYSTEM" = "centos" ]; then
# CentOS/RHEL
yum install -y epel-release
yum install -y nginx
systemctl enable nginx
systemctl start nginx
elif [ "$SYSTEM" = "debian" ] || [ "$SYSTEM" = "ubuntu" ]; then
# Debian/Ubuntu
apt-get update
apt-get install -y nginx
systemctl enable nginx
systemctl start nginx
fi
# 检查安装是否成功
if [ $? -eq 0 ]; then
echo -e "${GREEN}Nginx安装成功!${NC}"
else
echo -e "${RED}Nginx安装失败!${NC}"
exit 1
fi
}
# 配置防火墙
configure_firewall() {
echo -e "${YELLOW}配置防火墙...${NC}"
if command -v firewall-cmd &> /dev/null; then
# firewalld
firewall-cmd --permanent --zone=public --add-service=http
firewall-cmd --permanent --zone=public --add-service=https
firewall-cmd --reload
echo -e "${GREEN}防火墙已配置,允许HTTP/HTTPS流量${NC}"
elif command -v ufw &> /dev/null; then
# ufw
ufw allow 'Nginx Full'
echo -e "${GREEN}UFW已配置,允许Nginx流量${NC}"
else
echo -e "${YELLOW}未找到firewalld或ufw,跳过防火墙配置${NC}"
fi
}
# 验证安装
verify_installation() {
echo -e "${YELLOW}验证Nginx安装...${NC}"
nginx -v
systemctl status nginx --no-pager
IP=$(hostname -I | awk '{print $1}')
echo -e "\n${GREEN}Nginx已安装并运行!${NC}"
echo -e "您可以通过浏览器访问: http://${IP}"
}
# 主函数
main() {
check_system
install_nginx
configure_firewall
verify_installation
}
main
install_nginx.sh
bash
chmod +x install_nginx.sh
bash
sudo ./install_nginx.sh
systemctl status nginx
检查服务状态/etc/nginx/nginx.conf
/usr/share/nginx/html
如需进一步配置Nginx,可以编辑/etc/nginx/nginx.conf
或/etc/nginx/sites-available/
下的配置文件。