CentOS 7 配置启动 手动编译的 nginx
1.如何安装请参考之前的编译安装文章
手动编一个的nginx 一般在这个目录下:/usr/local/nginx
2.配置 Nginx 服务
2.1 创建 Systemd 服务文件
- 路径:
/etc/systemd/system/nginx.servicesudo vim /etc/systemd/system/nginx.service
- 内容:这里是推荐的配置文件:
[Unit] Description=The Nginx HTTP and reverse proxy server After=syslog.target 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
2.2 配置文件分析
- [Unit] 部分:
After=syslog.target network.target remote-fs.target nss-lookup.target:确保在其他服务启动后再启动 Nginx。
- [Service] 部分:
Type=forking:使用forking类型,Nginx 启动后会生成子进程。PIDFile:Nginx 主进程的 PID 文件路径。ExecStartPre:在启动前执行nginx -t命令,检查配置文件是否正确。ExecStart:启动 Nginx,指定配置文件路径。ExecReload:重新加载 Nginx 配置。ExecStop:优雅地停止 Nginx。PrivateTmp=true:为 Nginx 提供独立的临时文件夹,提升安全性。
2.3 重新加载 Systemd 服务文件
sudo systemctl daemon-reload
3. 配置 Nginx 日志文件
确保你在 Nginx 配置文件 /usr/local/nginx/conf/nginx.conf 中正确设置了日志路径。例如:
error_log /usr/local/nginx/logs/error.log;
access_log /usr/local/nginx/logs/access.log;
4. 启动 Nginx 服务
4.1 启动 Nginx
sudo systemctl start nginx
4.2 检查 Nginx 服务状态
sudo systemctl status nginx
确认 Nginx 是否启动成功。如果出现错误,可以通过查看日志来诊断:
sudo journalctl -u nginx.service
5. 设置 Nginx 开机自启
sudo systemctl enable nginx
这会将 Nginx 添加到系统启动项中,使其在系统重启时自动启动。
6. 调试与常见问题解决
6.1 检查配置文件语法
在启动 Nginx 之前,确保 Nginx 配置文件没有语法错误:

浙公网安备 33010602011771号