Zeynel
Zeynel

Reputation: 13525

When do we need to use http block in nginx config file?

I am reading nginx beginner's tutorial, on the section Serving Static Content they have

http {
  server {
  }
}

but when I add an http block I get the error

[emerg] "http" directive is not allowed here …

When I remove the http block and change the conf file to this, it works fine:

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /var/example.com/html;
    index index.html index.htm;

    # make site accessible from http://localhost/
    server_name localhost

    location / {
      try_files $uri $uri/ /index.html;
  }

I suspect that I am missing something simple, but why do they use http to serve static files?

Upvotes: 32

Views: 14549

Answers (1)

Ian
Ian

Reputation: 2021

Your doing fine. I guess you are editing /etc/nginx/sites-enabled/default (or the linked file at /etc/nginx/sites-available/default.

This is the standard nginx set up. It is configured with /etc/nginx/nginx.conf which contains the http {} statement. This in turn contains an "include /etc/nginx/sites-enabled/*" line to include your file above with server{ } clause in it.

Note that if you are using an editor that creates a backup file, you must modify the include statement to exclude the backup files, or you will get some "interesting" errors! My line is

include /etc/nginx/sites-enabled/*[a-zA-Z] 

which will not pick up backup files ending in a tilde. YMMV.

Upvotes: 37

Related Questions