安装Nginx + 日志管理

Install Nginx

Posted by byron han on March 20, 2026

本文首次发布于 Byron Han Blog, 作者 @han(Byron Han) ,转载请保留原文链接.

安装Nginx

wget -c http://nginx.org/download/nginx-1.29.5.tar.gz

安装依赖

yum install -y gcc-c++ zlib zlib-devel openssl openssl-devel pcre pcre-devel tar -zxvf nginx-1.29.5.tar.gz

cd nginx-1.29.5/

执行脚本进行配置

./configure --with-cc-opt='-g -O2' --prefix=/usr/local/nginx --with-http_ssl_module --with-http_realip_module --with-threads --with-http_v2_module --with-http_gzip_static_module --with-http_gzip_static_module yum -y install gcc gcc-c++ autoconf automake make

编译安装

make && make install

无Make 执行yum -y install gcc gcc-c++ autoconf automake make

使用systemctl 管理 nginx

vi /usr/lib/systemd/system/nginx.service

输入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=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 -q -g 'daemon on; master_process on;'
ExecStart=/usr/local/nginx/sbin/nginx -g 'daemon on; master_process on;'
ExecReload=/usr/local/nginx/sbin/nginx -g 'daemon on; master_process on;' -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
TimeoutStartSec=30
PIDFileMode=0644
Restart=on-failure

[Install]
WantedBy=multi-user.target

Nginx 日志管理

shell 脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/bin/bash

# 定义日志目录
LOG_DIR="/usr/local/nginx/logs"  # Nginx 日志目录
DAYS_TO_KEEP=7           # 保留最近多少天的日志

# 检查日志目录是否存在
if [ ! -d "$LOG_DIR" ]; then
  echo "错误:日志目录 $LOG_DIR 不存在!"
  exit 1
fi

# 获取昨天的日期(用于日志切割)
YESTERDAY=$(date -d "yesterday" +%Y-%m-%d)

# 切割日志文件
if [ -f "$LOG_DIR/access.log" ]; then
  mv "$LOG_DIR/access.log" "$LOG_DIR/access_$YESTERDAY.log"
fi

if [ -f "$LOG_DIR/error.log" ]; then
  mv "$LOG_DIR/error.log" "$LOG_DIR/error_$YESTERDAY.log"
fi

# 向 Nginx 主进程发送 USR1 信号,重新打开日志文件
if [ -f /usr/local/nginx/logs/nginx.pid ]; then
  kill -USR1 $(cat /usr/local/nginx/logs/nginx.pid)
fi

# 压缩昨天的日志文件
if [ -f "$LOG_DIR/access_$YESTERDAY.log" ]; then
  gzip "$LOG_DIR/access_$YESTERDAY.log"
fi

if [ -f "$LOG_DIR/error_$YESTERDAY.log" ]; then
  gzip "$LOG_DIR/error_$YESTERDAY.log"
fi

# 清理 30 天前的旧日志文件
find "$LOG_DIR" -type f -name "access_*.log.gz" -mtime +$DAYS_TO_KEEP -exec rm -f {} \;
find "$LOG_DIR" -type f -name "error_*.log.gz" -mtime +$DAYS_TO_KEEP -exec rm -f {} \;

# 记录操作日志
echo "$(date '+%Y-%m-%d %H:%M:%S') - 日志已切割、压缩并清理完成。" >> "$LOG_DIR/nginx_log_cleanup.log"

添加执行权限

1
chmod +x /usr/local/bin/rotate_compress_clean_nginx_logs.sh

每天自动运行

1
2
3
crontab -e

0 0 * * * /usr/local/bin/rotate_compress_clean_nginx_logs.sh