How to Fix Nginx Access Log Configuration Error
In this tutorial, you'll learn about How to Fix Nginx Access Log Configuration Error. We cover key concepts, practical examples, and best practices.
Nginx access logs are empty, show - for expected values, or the wrong log format is applied — the log_format is not referenced by any access_log directive or the format string has errors.
The Problem
# Wrong: Format defined but not referenced
http {
log_format custom '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent';
server {
access_log /var/log/nginx/access.log;
# Uses default format, not 'custom'
}
}
Step-by-Step Fix
Step 1: Define and reference the log format
http {
log_format json_log escape=json
'{'
'"time":"$time_iso8601",'
'"remote_addr":"$remote_addr",'
'"request":"$request",'
'"status":$status,'
'"body_bytes":$body_bytes_sent,'
'"referer":"$http_referer",'
'"user_agent":"$http_user_agent",'
'"request_time":$request_time'
'}';
server {
access_log /var/log/nginx/access.log json_log;
}
}
Step 2: Use conditional logging
map $status $loggable {
~^[23] 0;
default 1;
}
server {
access_log /var/log/nginx/access.log combined if=$loggable;
}
Step 3: Disable access logging for static files
location ~* \.(css|js|png|jpg)$ {
access_log off;
}
Step 4: Test log output
curl http://localhost/
tail -1 /var/log/nginx/access.log
Step 5: Set up log rotation
# /etc/logrotate.d/nginx
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 640 nginx adm
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
endscript
}
Prevention Tips
- Use JSON log format for structured log parsing
- Rotate logs daily to prevent disk space issues
- Use conditional logging to reduce noise
- Monitor log file size with
logrotatealerts
Common Mistakes with access log
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world NGINX code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro