一、简介
为了方便调用nginx,在服务器中我们通常采用shell来做一键操作,如启动停止以及重启等相关操作。这样即简化了操作,也避免了有时疏忽大意执行错了命令。
二、shell脚本内容
1、首先创建nginx启动脚本,如nginx_ctl.sh
touch nginx_ctl.sh
chmod 777 nginx_ctl.sh
2、然后编写shell脚本如下:
#vim nginx_ctl.sh
#!/bin/sh
#
# nginx - this script starts and stops the nginx daemin
#
# chkconfig: - 85 15
# description: Nginx is an HTTP(S) server, HTTP(S) reverse \
# proxy and IMAP/POP3 proxy server
# processname: nginx
# config: /usr/local/nginx/conf/nginx.conf
# pidfile: /usr/local/nginx/logs/nginx.pid
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0
nginx="/opt/nginx/sbin/nginx" # nginx启动执行路径
prog=$(basename $nginx)
pidfile="/opt/nginx/logs/${prog}.pid" # nginx对应的pid文件
NGINX_CONF_FILE="/opt/nginx/conf/nginx.conf" # nginx对应的conf文件
lockfile=/var/lock/subsys/nginx
start() {
[ -x $nginx ] || exit 5
[ -f $NGINX_CONF_FILE ] || exit 6
echo -n $"Starting $prog: "
daemon $nginx -c $NGINX_CONF_FILE
retval=$?
echo
[ $retval -eq 0 ] && touch $lockfile
return $retval
}
stop() {
echo -n $"Stopping $prog: "
killproc -p $pidfile $prog -QUIT
retval=$?
echo
[ $retval -eq 0 ] && rm -f $lockfile
return $retval
}
restart() {
configtest || return $?
stop
start
}
reload() {
configtest || return $?
echo -n $"Reloading $prog: "
killproc -p $pidfile $nginx -HUP
RETVAL=$?
echo
}
force_reload() {
restart
}
configtest() {
$nginx -t -c $NGINX_CONF_FILE
}
rh_status() {
status -p $pidfile $prog
}
rh_status_q() {
rh_status >/dev/null 2>&1
}
case "$1" in
start)
rh_status_q && exit 0
$1
;;
stop)
rh_status_q || exit 0
$1
;;
restart|configtest)
$1
;;
reload)
rh_status_q || exit 7
$1
;;
force-reload)
force_reload
;;
status)
rh_status
;;
condrestart|try-restart)
rh_status_q || exit 0
;;
*)
echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configt
est}"
exit 2
esac
3、然后可以进行如下操作
./nginx_ctl start # 启动nginx
./nginx_ctl stop # 停止nginx
./nginx_ctl restart # 重启nginx