#!/bin/bash
# 定义Nginx源代码下载地址和安装目录
NGINX_SOURCE_URL="http://nginx.org/download/nginx-1.18.0.tar.gz"
NGINX_SOURCE_TAR="nginx-1.18.0.tar.gz"
NGINX_SOURCE_DIR="nginx-1.18.0"
INSTALL_DIR="/usr/local/nginx"
# 编译安装Nginx
install_nginx() {
echo "开始安装Nginx..."
# 下载Nginx源代码
wget $NGINX_SOURCE_URL
# 解压源代码
tar zxvf $NGINX_SOURCE_TAR
cd $NGINX_SOURCE_DIR
# 配置安装选项
./configure --prefix=$INSTALL_DIR
# 编译和安装
make && make install
echo "Nginx安装完成."
}
# 启动Nginx服务
start_nginx() {
echo "启动Nginx..."
$INSTALL_DIR/sbin/nginx
echo "Nginx已启动."
}
# 停止Nginx服务
stop_nginx() {
echo "停止Nginx..."
$INSTALL_DIR/sbin/nginx -s stop
echo "Nginx已停止."
}
# 设置开机自启动(CentOS 6)
setup_autostart_centos6() {
echo "设置CentOS 6开机自启动..."
# 创建chkconfig脚本
cat > /etc/init.d/nginx <<EOF
#!/bin/bash
# chkconfig: 345 85 15
# description: Nginx web server
case "\$1" in
start)
$INSTALL_DIR/sbin/nginx
;;
stop)
$INSTALL_DIR/sbin/nginx -s stop
;;
restart)
$INSTALL_DIR/sbin/nginx -s stop
$INSTALL_DIR/sbin/nginx
;;
*)
echo "Usage: \$0 {start|stop|restart}"
exit 1
esac
EOF
# 使脚本可执行
chmod +x /etc/init.d/nginx
# 添加到chkconfig
chkconfig --add nginx
chkconfig nginx on
echo "CentOS 6开机自启动设置完成."
}
# 设置开机自启动(CentOS 7)
setup_autostart_centos7() {
echo "设置CentOS 7开机自启动..."
# 创建systemd服务文件
cat > /etc/systemd/system/nginx.service <<EOF
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=network.target
[Service]
Type=forking
ExecStart=$INSTALL_DIR/sbin/nginx
ExecReload=$INSTALL_DIR/sbin/nginx -s reload
ExecStop=$INSTALL_DIR/sbin/nginx -s quit
PrivateTmp=true
[Install]
WantedBy=multi-user.target
EOF
# 重新加载systemd管理配置
systemctl daemon-reload
# 启用Nginx服务
systemctl enable nginx
echo "CentOS 7开机自启动设置完成."
}
# 根据系统版本选择设置方法
if [ -f /etc/redhat-release ]; then
version=$(cat /etc/redhat-release)
if [[ $version == *"CentOS release 6"* ]]; then
setup_autostart_centos6
elif [[ $version == *"CentOS Linux release 7"* ]]; then
setup_autostart_centos7
else
echo "不支持的CentOS版本"
fi
else
echo "这不是一个CentOS系统"
fi
# 解析命令行参数执行相应操作
case $1 in
install)
install_nginx
;;
start)
start_nginx
;;
stop)
stop_nginx
;;
*)
echo "Usage: $0 {install|start|stop}"
exit 1
esac
通过shell编程实现:开发 Nginx 服务(编译安装)启动停止脚本
最新推荐文章于 2024-01-04 14:12:03 发布