使用nginx的简单反向代理

时间:2014-10-15 21:25:07

标签: nginx proxy

我正在http://localhost:3000上运行Rails应用,我希望以http://localhost方式访问该应用。我正在尝试使用nginx进行反向代理,看起来它应该很简单,但我还没有让它工作。我可以在http://localhost:3000访问我的应用,但我在http://localhost没有回复。这是我第一次玩弄nginx,所以我不确定是什么错,在哪里寻找更多细节。我还查看了10多个Stack Overflow问题,nginx教程和问题,但到目前为止它们都没有帮助过我。

这是一个/etc/nginx/nginx.conf的片段

user www-data;
worker_processes  1;

error_log  /var/log/nginx/error.log;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
    # multi_accept on;
}

http {
    include       /etc/nginx/mime.types;

    access_log  /var/log/nginx/access.log;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;
    tcp_nodelay        on;

    gzip  on;
    gzip_disable "MSIE [1-6]\.(?!.*SV1)";

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

conf.d目录中唯一的.conf文件:/etc/nginx/conf.d/default.conf

upstream backend {
    server 127.0.0.1:3000;
}

server {
    listen 80;

    server_name localhost;

    access_log  /var/log/nginx/localhost.access.log;
    location / {
        proxy_pass http://backend;
        proxy_redirect off;
        proxy_set_header   Host             $host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header  X-Forwarded-Proto  http;
        proxy_set_header X-NginX-Proxy true;
    }
}

我按照this page进行了设置。

此外,/ etc / nginx / sites-enabled / default的内容,也是启用网站的目录中的唯一文件

server {
    listen   80 default;
    server_name  localhost;

    access_log  /var/log/nginx/localhost.access.log;

    location / {
            root   /var/www/nginx-default;
            index  index.html index.htm;
    }

    location /doc {
            root   /usr/share;
            autoindex on;
            allow 127.0.0.1;
            deny all;
    }

    location /images {
            root   /usr/share;
            autoindex on;
    }
}

当我重新启动nginx ...(输出)

$ sudo service nginx restart
Restarting nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
configuration file /etc/nginx/nginx.conf test is successful
nginx.

我在日志中看到了这一点:

2014/10/15 23:28:12 [warn] 5800#0: conflicting server name "localhost" on 0.0.0.0:80, ignored

2 个答案:

答案 0 :(得分:0)

更改默认端口:rails s -p 80

答案 1 :(得分:0)

问题是服务器localhost:80被定义了两次:

  • in" conf.d / default.conf"
  • 和"网站启用/默认"

和nginx在请求" localhost:80"时会感到困惑。到达 - 哪个服务器应该提供请求???

您应该替换" conf.d / default.conf"中的server块。包含"网站启用/默认"中server块内容的文件(从那里删除)。

因为" conf.d / * .conf"文件用于配置模块\功能,而不是用于托管描述的服务器。