nginx unknown directive “upstream”

2019-03-11 02:26发布

问题:

I'm using nginx as a proxy server to forward requests onto my gunicorn server. When I run sudo nginx -t -c /etc/nginx/sites-enabled/mysite I get the following error.

[emerg]: unknown directive "upstream" in /etc/nginx/sites-enabled/mysite:1
configuration file /etc/nginx/sites-enabled/mysite test failed

Any idea how to fix it? This is my nginx config:

upstream gunicorn_mysite {
    server 127.0.0.1:8000 fail_timeout=0;
}

server {
    listen 80;
    server_name example.com;

    access_log /usr/local/django/logs/nginx/mysite_access.log;
    error_log /usr/local/django/logs/nginx/mysite_error.log;

    location / {
        proxy_pass http://gunicorn_mysite;
    }
}

I'm running Ubuntu 10.04 and my nginx version is 0.7.65 which I installed from apt.

This is the output when I run nginx -V

nginx version: nginx/0.7.65
TLS SNI support enabled
configure arguments: --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --pid-path=/var/run/nginx.pid --lock-path=/var/lock/nginx.lock --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/lib/nginx/body --http-proxy-temp-path=/var/lib/nginx/proxy --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --with-debug --with-http_stub_status_module --with-http_flv_module --with-http_ssl_module --with-http_dav_module --with-http_gzip_static_module --with-http_realip_module --with-mail --with-mail_ssl_module --with-ipv6 --add-module=/build/buildd/nginx-0.7.65/modules/nginx-upstream-fair

回答1:

When you tell nginx to load that file directly, it starts at the global context. The upstream directive is only valid in the http context. When that file is included normally by nginx.conf, it is included already inside the http context:

events { }
http {
  include /etc/nginx/sites-enabled/*;
}

You either need to use -c /etc/nginx/nginx.conf or make a small wrapper like the above block and nginx -c it.



回答2:

I am using nginx version: nginx/1.4.1 on EC2 Ubuntu. I was getting this error:

nginx: [emerg] "upstream" directive is not allowed here in /etc/nginx/nginx.conf

To get my instance running I had to wrap the upstream and server sections in an http { } section. It then complained about missing event section. So I added that as follows:

events { worker_connections 1024; }

It worked fine after those fixes, this is my first effort so I was guessing my way through.



回答3:

Turns my nginx config was ok. The problem was with my gunicorn server was not running properly.