如何配置nginx开机自启
时间: 2023-11-07 15:13:09 浏览: 94
在Linux系统中,可以通过以下步骤配置Nginx开机自启:
1. 打开Nginx的系统服务脚本文件:`sudo nano /etc/init.d/nginx`
2. 在脚本文件中添加以下内容:
```
#!/bin/sh
### BEGIN INIT INFO
# Provides: nginx
# Required-Start: $remote_fs $network
# Required-Stop: $remote_fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: starts the nginx web server
# Description: starts nginx using start-stop-daemon
### END INIT INFO
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/local/nginx/sbin/nginx
NAME=nginx
DESC=nginx
test -x $DAEMON || exit 0
# Include nginx defaults if available
if [ -f /etc/default/nginx ] ; then
. /etc/default/nginx
fi
set -e
case "$1" in
start)
echo -n "Starting $DESC: "
start-stop-daemon --start --quiet --pidfile /usr/local/nginx/logs/$NAME.pid \
--exec $DAEMON -- $DAEMON_OPTS || true
echo "$NAME."
;;
stop)
echo -n "Stopping $DESC: "
start-stop-daemon --stop --quiet --pidfile /usr/local/nginx/logs/$NAME.pid \
--exec $DAEMON || true
echo "$NAME."
;;
restart|force-reload)
echo -n "Restarting $DESC: "
start-stop-daemon --stop --quiet --pidfile \
/usr/local/nginx/logs/$NAME.pid --exec $DAEMON || true
sleep 1
start-stop-daemon --start --quiet --pidfile \
/usr/local/nginx/logs/$NAME.pid --exec $DAEMON -- $DAEMON_OPTS || true
echo "$NAME."
;;
reload)
echo -n "Reloading $DESC configuration: "
start-stop-daemon --stop --signal HUP --quiet --pidfile /usr/local/nginx/logs/$NAME.pid \
--exec $DAEMON || true
echo "$NAME."
;;
status)
status_of_proc -p /usr/local/nginx/logs/$NAME.pid "$DAEMON" nginx && exit 0 || exit $?
;;
*)
N=/etc/init.d/$NAME
echo "Usage: $N {start|stop|restart|reload|force-reload|status}" >&2
exit 1
;;
esac
exit 0
```
3. 保存脚本文件并退出编辑器。
4. 将脚本文件设置为可执行权限:`sudo chmod +x /etc/init.d/nginx`
5. 启用系统服务:`sudo systemctl daemon-reload`
6. 设置Nginx开机自启:`sudo systemctl enable nginx`
现在,当你重启系统后,Nginx将自动启动。你也可以使用以下命令手动启动、停止或重启Nginx:
- 启动:`sudo systemctl start nginx`
- 停止:`sudo systemctl stop nginx`
- 重启:`sudo systemctl restart nginx`
阅读全文