改脚本为下载源文件编译安装,可以根据自己需求进行各种修改,简单快捷,分享给大家使用
#!/bin/bash
# 设置变量:Nginx 版本号
nginx_version="1.24.0"
nginx_tarball="nginx-${nginx_version}.tar.gz"
nginx_dir="nginx-${nginx_version}"
# 颜色定义
COLOR_RED='\033[0;31m'
COLOR_GREEN='\033[0;32m'
COLOR_YELLOW='\033[0;33m'
COLOR_RESET='\033[0m'
# 函数:打印红色日志
print_red() {
echo -e "${COLOR_RED}$1${COLOR_RESET}"
}
# 函数:打印绿色日志
print_green() {
echo -e "${COLOR_GREEN}$1${COLOR_RESET}"
}
# 函数:打印黄色日志
print_yellow() {
echo -e "${COLOR_YELLOW}$1${COLOR_RESET}"
}
# 检查当前用户是否具有足够权限
if [ "$(id -u)" != "0" ]; then
print_red "错误: 请使用 root 权限运行此脚本。"
exit 1
fi
# 打印黄色日志:检查是否已经下载 Nginx 源代码压缩包
if [ -f "$nginx_tarball" ]; then
print_yellow "已经下载了 Nginx 源代码压缩包"
else
# 打印黄色日志:下载 Nginx 源代码压缩包
print_green "下载 Nginx 源代码压缩包"
wget http://nginx.org/download/$nginx_tarball
fi
# 如果解压后的文件夹已经存在,则删除老的文件夹
if [ -d "$nginx_dir" ]; then
print_yellow "删除老的 Nginx 文件夹: $nginx_dir"
sudo rm -rf $nginx_dir
fi
# 打印黄色日志:解压源代码压缩包
print_green "解压源代码压缩包"
tar -zxvf $nginx_tarball
# 进入解压后的 Nginx 目录
print_green "进入解压后的 Nginx 目录: $nginx_dir"
cd $nginx_dir
# 打印黄色日志:安装编译 Nginx 所需的依赖
print_green "安装编译 Nginx 所需的依赖"
sudo yum install -y gcc gcc-c++ make automake autoconf libtool zlib zlib-devel openssl openssl-devel pcre pcre-devel
# 打印黄色日志:配置编译选项,指定安装路径等
print_green "配置编译选项,指定安装路径等"
./configure --prefix=/usr/local/nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-stream \
--with-stream_ssl_module \
--with-stream_realip_module \
--with-stream_ssl_preread_module \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--with-http_realip_module \
--with-http_addition_module \
--with-http_sub_module \
--with-http_flv_module \
--with-http_mp4_module \
--with-http_secure_link_module \
--with-http_random_index_module \
--with-http_degradation_module \
--with-http_slice_module
# 打印黄色日志:编译 Nginx
print_green "编译 Nginx"
make
# 打印黄色日志:安装 Nginx
print_green "安装 Nginx"
sudo make install
# 打印黄色日志:启动 Nginx 服务
print_green "启动 Nginx 服务"
sudo /usr/local/nginx/sbin/nginx
# 打印黄色日志:可选,设置开机自启动
print_yellow "设置开机自启动"
# 创建 Nginx 服务文件
print_yellow "创建 Nginx 服务文件"
sudo cat << EOF > /etc/systemd/system/nginx.service
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/bin/kill -s HUP \$MAINPID
ExecStop=/bin/kill -s QUIT \$MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
EOF
# 重新加载 systemd 配置
print_yellow "重新加载 systemd 配置"
sudo systemctl daemon-reload
# 启用 Nginx 服务并设置为开机自启动
print_yellow "启用 Nginx 服务并设置为开机自启动"
sudo systemctl enable nginx
print_yellow "Nginx 自启动设置完成。"