Problem: Nginx Server Directive Error
When setting up Nginx, you might see the error message '[emerg] "server" directive is not allowed here'. This error happens when you put the server directive in the wrong place in the Nginx configuration file. It means Nginx can't use the configuration because of this mistake, which can stop the web server from starting or reloading properly.
Solutions to Fix the '[emerg] "server" directive is not allowed here' Error
Proper Structure of Nginx Configuration File
To fix the '[emerg] "server" directive is not allowed here' error, you need to structure your Nginx configuration file correctly. The server block must be inside an http block. Here's how to do it:
- Open your main Nginx configuration file (/etc/nginx/nginx.conf).
- Find the http block. If it's missing, add it:
http {
# Your server blocks go here
}
- Put your server block inside the http block:
http {
server {
# Your server configuration
}
}
- Check the structure of your nginx.conf file to make sure it follows this layout:
events {
# Event context settings
}
http {
# Global HTTP settings
server {
# Server block 1
}
server {
# Server block 2
}
}
Using Include Directives for Modular Configuration
You can use include directives to split your configuration across multiple files:
- In your main nginx.conf file, add an include statement within the http block:
http {
include /etc/nginx/sites-enabled/*;
}
-
Create separate configuration files for each server block in the /etc/nginx/sites-available/ directory.
-
To activate a configuration, create a symbolic link from sites-available to sites-enabled:
sudo ln -s /etc/nginx/sites-available/your-config /etc/nginx/sites-enabled/
This method keeps your main configuration file clean and makes it easier to manage multiple server blocks.
Checking Syntax and Testing Configuration
Before applying changes to your Nginx configuration, always test it:
- Use the nginx -t command to check for syntax errors:
sudo nginx -t
-
If there are errors, the command will show you the line number and file where the problem is.
-
Fix any issues and run the test again until you get a success message.
-
Once the test passes, reload Nginx to apply the changes:
sudo systemctl reload nginx