为什么我无法通过nginx proxy pass访问子域?

Why I can't access to subdomain through nginx proxy pass?

我想通过 Nginx 和 RoR 网络服务器(如 UnicornThinWEBrick).

如下所示,我想通过 post 子域访问我的网络应用程序:

upstream sub {
  server unix:/tmp/unicorn.subdomain.sock fail_timeout=0;
#  server 127.0.0.1:3000;
}

server {
  listen   80;
  server_name post.subdomain.me;

  access_log /var/www/subdomain/log/access.log;
  error_log  /var/www/subdomain/log/error.log;
  root     /var/www/subdomain;
  index    index.html;

  location / {
    proxy_set_header  X-Real-IP  $remote_addr;
    proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header  Host $http_host;
    proxy_redirect  off;
    try_files /system/maintenance.html $uri $uri/index.html $uri.html @ruby;
  }

  location @ruby {
    proxy_pass http://sub;
  }
}

一切正常,当我输入 post.subdomain.me 时,我可以看到我的 RoR 应用程序。

问题: 当我使用 post.subdomain.me url 我无法访问我的子域(request.subdomain returns 空request.host returns subdomain 代替了 subdomain.me)。但是当我使用 post.subdomain.me:3000 时,一切都很完美(我失去了一半的头发才意识到这一点)。为什么以及如何解决?

当您使用端口访问应用程序时 - 您正在直接访问 rails 服务器,而不是通过 nginx 代理,这对于调试来说很好,但通常不适合生产。

可能主机头没有被客户端传递过来,$host默认为nginx主机

尝试

location @ruby {
    proxy_set_header Host $host;
    proxy_pass http://sub;
}

还有一个'hardcode'方式:proxy_set_header Host post.subdomain.me;

proxy_set_headerproxy_redirect 指令配置 proxy_pass 指令并且需要在同一位置块内或从封闭的 server 块继承。您需要像这样格式化您的配置文件:

location / {
    try_files /system/maintenance.html $uri $uri/index.html $uri.html @ruby;
}

location @ruby {
    proxy_set_header  X-Real-IP  $remote_addr;
    proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header  Host $http_host;
    proxy_redirect  off;
    proxy_pass http://sub;
}

编辑:假设 nginx 没有像@Vasfed 建议的那样正确地将信息传递给 RoR,请尝试 proxy_set_header Host 的其他值。还有其他三个候选项,意思都略有不同。

    proxy_set_header  Host post.subdomain.me;
    proxy_set_header  Host $server_name;
    proxy_set_header  Host $host;