How to Fix Nginx Configuration Test and Validation Error
In this tutorial, you'll learn about How to Fix Nginx Configuration Test and Validation Error. We cover key concepts, practical examples, and best practices.
Nginx configuration test fails with nginx: [emerg] unknown directive or test failed when running nginx -t — the configuration file has a syntax error, missing semicolon, or invalid directive name.
The Problem
$ sudo nginx -t
nginx: [emerg] unknown directive "server_name" in /etc/nginx/sites-enabled/example.com:5
nginx: configuration file /etc/nginx/nginx.conf test failed
Step-by-Step Fix
Step 1: Check the specific file and line
sudo nginx -t 2>&1
# Shows exact file and line number of the error
Step 2: View the problematic line
sudo sed -n '5p' /etc/nginx/sites-enabled/example.com
Step 3: Fix common syntax errors
# Wrong: missing semicolon
server_name example.com
# Right: semicolon at the end
server_name example.com;
# Wrong: block missing closing brace
server {
listen 80;
# Right: proper block structure
server {
listen 80;
}
Step 4: Validate all included files
# Test only specific config
sudo nginx -t -c /etc/nginx/sites-enabled/example.com
# Test with verbose output
sudo nginx -T | grep -n "server_name"
Step 5: Check for duplicate server blocks
sudo nginx -T | grep -c "server_name example.com"
Prevention Tips
- Run
nginx -tbefore every reload - Use
includedirectives for modular configuration - Version control your Nginx configs with git
- Use a linter like
gixyto identify security issues
Common Mistakes with config test
- 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