---
title: "Linux配置nginx为服务"
author: "xinlanzero"
date: "2011-08-08T17:29:21Z"
tags: []
categories: ["Web前端"]
slug: "linux-nginx"
draft: false
lastmod: "2011-08-08T17:50:07Z"
id: 1142825
url: "https://xinlanzero.iteye.com/blog/1142825"
---

一个在Linux下的nginx服务脚本  
支持 启动／关闭／重启／状态／进程信息／测试配置文件

#!/bin/bash  
\# chkconfig: 2345 58 74  
\#  
\# nginx – This shell script takes care of starting and stopping nginx.  
\#  
\# desc: nginx \[engine x] is light and fast http web/proxy server

nginx\_path=/usr/local/nginx  
nginx\_exec=$nginx\_path/sbin/nginx  
nginx\_conf=$nginx\_path/conf/nginx.conf  
nginx\_pid=$nginx\_path/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

\[ -x $nginx\_exec ] || exit 0

retval=0  
exec=”nginx”

\# Start daemons.  
start() {  
if \[ -e $nginx\_pid -a ! -z $nginx\_pid ];then  
echo “nginx already running…”  
exit 1  
fi

if \[ -e $nginx\_conf ];then  
echo -n $”Starting $exec: ”  
$nginx\_exec -c $nginx\_conf &  
retval=$?  
\[ $retval -eq 0 ] && {  
touch /var/lock/subsys/$exec  
success $”$exec”  
}  
echo  
else  
retval=1  
fi  
return $retval  
}

\# Stop daemons.  
stop() {  
echo -n $”Stopping $exec: ”  
killproc -d 10 $nginx\_exec  
retval=$?  
echo  
\[ $retval = 0 ] && rm -f $nginx\_pid /var/lock/subsys/$exec  
}

reload() {  
echo -n $”Reloading $exec: ”  
ps auxww | grep nginx | grep master | awk ‘{print $2}’ | xargs kill -HUP  
success $”$exec”  
echo  
}

test() {  
$nginx\_exec -t -c $nginx\_conf  
}

\# See how we were called.  
case “$1″ in  
start)  
start  
;;

stop)  
stop  
;;

restart)  
stop  
start  
;;

status)  
status $exec  
retval=$?  
;;

show)  
ps -aux|grep nginx  
;;

reload)  
reload  
;;

test)  
test  
;;

\*)  
echo $”Usage: $0 {start|stop|restart|status|show|reload|test}”  
exit 1  
esac

exit $retval

\# 脚本名称 nginx , 需要将该脚本复制到 /etc/rc.d/init.d 并执行以下命令  
\# chmod 755 nginx  
\# chkconfig --add nginx  
\# 此方法可能仅限红帽系列的Linux，包括CentOS。测试环境rhel6.0