Nginx 개별 서버마다 로그 설정하기

Nginx 개별 서버(가상 호스트)마다 로그를 설정하려면 access_logerror_log 지시어를 각 server 블록 내에 설정하면 됩니다.

다음의 경로로 접속한 다음, access와 error로 시작하는 모든 파일을 삭제한다.

cd /var/log/nginx
find . -type f -name 'access*' -exec rm {} \;
find . -type f -name 'error*' -exec rm {} \;

개별 서버별 로그 생성하기

우선 전역적으로 설정한 access.log와 error.log 설정을 주석처리한다. etc/nginx/nginx.conf 파일에서 다음의 코드를 주석처리한다.

# access_log /var/log/nginx/access.log;
# error_log /var/log/nginx/error.log;

다음은 서버 별로 폴더를 만들어 access.log와 error.log를 다시 생성했다. 그 다음은 sites-available 폴더의 개별 서버 설정에서 다음과 같은 코드를 작성한다. access_log와 error_log의 경로는 개별 파일이 있는 경로를 작성해주면 된다.

예제: 개별 서버별 로그 설정

http {
    log_format custom_format '$remote_addr - $remote_user [$time_local] '
                             '"$request" $status $body_bytes_sent '
                             '"$http_referer" "$http_user_agent"';

    server {
        listen 80;
        server_name example1.com;
        
        access_log /var/log/nginx/example1_access.log custom_format;
        error_log /var/log/nginx/example1_error.log warn;

        location / {
            root /var/www/example1;
            index index.html;
        }
    }

    server {
        listen 80;
        server_name example2.com;
        
        access_log /var/log/nginx/example2_access.log custom_format;
        error_log /var/log/nginx/example2_error.log warn;

        location / {
            root /var/www/example2;
            index index.html;
        }
    }
}

설명

  1. 로그 형식 지정
    • log_format custom_format ...;
      커스텀 로그 형식을 정의하여, 이후 access_log에서 사용 가능하게 설정합니다.
  2. 개별 서버 블록에 로그 설정
    • access_log /var/log/nginx/example1_access.log custom_format;
      example1.com의 접근 로그를 별도 파일에 저장합니다.
    • error_log /var/log/nginx/example1_error.log warn;
      example1.com의 에러 로그를 별도 파일에 저장합니다.
    • example2.com도 동일한 방식으로 별도 로그 설정이 가능합니다.

추가 설정

1. 로그 없는 서버 설정

server {
    listen 80;
    server_name no-logs.example.com;
    
    access_log off;
    error_log /dev/null crit;
}

access_log off;error_log /dev/null crit;을 설정하면 해당 서버의 로그 기록을 남기지 않습니다.

2. 압축 및 로그 로테이션 설정

  • /etc/logrotate.d/nginx 파일 수정 (로그 파일 크기 제한 및 자동 압축)
/var/log/nginx/*.log {
    daily
    rotate 14
    compress
    delaycompress
    missingok
    notifempty
    sharedscripts
    postrotate
        systemctl reload nginx > /dev/null 2>&1 || true
    endscript
}

→ 하루마다(daily) 로그를 새 파일로 교체하고, 14일간 보관(rotate 14)하며 압축(compress)합니다.

이 설정을 적용한 후 nginx -t로 문법 검사를 하고, 문제가 없으면 systemctl reload nginx로 설정을 반영하면 됩니다. 🚀

Leave a Reply

Your email address will not be published. Required fields are marked *