How To Fix '[emerg] server directive is not allowed here' Error In Nginx?

Published July 12, 2024

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:

  1. Open your main Nginx configuration file (/etc/nginx/nginx.conf).
  2. Find the http block. If it's missing, add it:
http {
    # Your server blocks go here
}
  1. Put your server block inside the http block:
http {
    server {
        # Your server configuration
    }
}
  1. 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:

  1. In your main nginx.conf file, add an include statement within the http block:
http {
    include /etc/nginx/sites-enabled/*;
}
  1. Create separate configuration files for each server block in the /etc/nginx/sites-available/ directory.

  2. 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:

  1. Use the nginx -t command to check for syntax errors:
sudo nginx -t
  1. If there are errors, the command will show you the line number and file where the problem is.

  2. Fix any issues and run the test again until you get a success message.

  3. Once the test passes, reload Nginx to apply the changes:

sudo systemctl reload nginx