linux下安装nginx后开机启动篇

时间:2021-03-27 01:40:41

众所周知nginx安装后需要手动去启动,每次开机之后都要执行nginx的启动命令很蛋疼。那么我们来让nginx开机启动吧

1、先創建一個nginx文件把

[root@localhost ~]# vi /etc/init.d/nginx   #这个命令可以直接创建一个nginx文件

2、把下面的代碼拷貝到剛剛創建的nginx文件里

#!/bin/bash
# nginx Startup script for the Nginx HTTP Server
# it is v.0.0. version.
# chkconfig: -
# description: Nginx is a high-performance web and proxy server.
# It has a lot of features, but it's not for everyone.
# processname: nginx
# pidfile: /var/run/nginx.pid
# config: /usr/local/nginx/conf/nginx.conf
nginxd=/usr/local/nginx/sbin/nginx
nginx_config=/usr/local/nginx/conf/nginx.conf
nginx_pid=/usr/local/nginx/logs/nginx.pid

RETVAL=
prog="nginx"
# Source function library.
. /etc/rc.d/init.d/functions
# Source networking configuration.
. /etc/sysconfig/network
# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit
[ -x $nginxd ] || exit
# Start nginx daemons functions.
start() {
if [ -e $nginx_pid ];then
echo "nginx already running...."
exit
fi
echo -n $"Starting $prog: "
daemon $nginxd -c ${nginx_config}
RETVAL=$?
echo
[ $RETVAL = ] && touch /var/lock/subsys/nginx
return $RETVAL
}
# Stop nginx daemons functions.
stop() {
echo -n $"Stopping $prog: "
killproc $nginxd
RETVAL=$?
echo
[ $RETVAL = ] && rm -f /var/lock/subsys/nginx /usr/local/nginx/logs/nginx.pid
}
# reload nginx service functions.
reload() {
echo -n $"Reloading $prog: "
#kill -HUP `cat ${nginx_pid}`
killproc $nginxd -HUP
RETVAL=$?
echo
}
# See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
reload)
reload
;;
restart)
stop
start
;;
status)
status $prog
RETVAL=$?
;;
*)
echo $"Usage: $prog {start|stop|restart|reload|status|help}"
exit
esac
exit $RETVAL

注意:紅色加粗的路徑改為自己的路徑

3、給nginx文件權限

[root@localhost ~]# chmod a+x /etc/init.d/nginx

4、這一部是很重要的一步。把nginx加進開機確定的服務中

[root@localhost ~]# chkconfig --add nginx
[root@localhost ~]# chkconfig --level 35 nginx on #启动nginx的级别

也可以直接把nginx的启动项加到开机执行脚本中

[root@localhost ~]# vi /etc/rc.local  #打开local文件,在后面加入代码:/etc/init.d/nginx start

好了,重启下linux试试效果吧

[root@localhost ~]# reboot  #重启linux命令

刷新浏览器是不是可以了

以后就可以通过以下命令来操作nginx
启动:service nginx start
关闭:service nginx stop
重起:service nginx restart