【问题标题】:Why I can't access to subdomain through nginx proxy pass?为什么我无法通过 nginx 代理通行证访问子域?
【发布时间】:2016-03-16 14:52:37
【问题描述】:

我想通过Nginx 和RoR Web 服务器(如UnicornThinWEBrick)在我的本地计算机上部署我的Ruby on Rails 应用程序。

如下图,我想通过post子域访问我的web-app:

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 返回空,request.host 返回subdomain instaed of subdomain.me)。但是当我使用post.subdomain.me:3000 时,一切都很完美(我失去了一半的头发才意识到这一点)。为什么以及如何解决?

【问题讨论】:

  • 你用什么做HTTP服务器?您提到了 Unicorn、Thin 和 Webrick,但没有说明您尝试了哪一种。
  • @TomL:所有这些我都有同样的问题。
  • 您所有的proxy_xxx 指令都位于错误的location 块中。您需要将它们与location @ruby 块中的proxy_pass 指令一起保留,否则它们将被忽略。
  • @RichardSmith:您能否详细描述一下您的回答?

标签: ruby-on-rails ubuntu nginx unicorn


【解决方案1】:

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;

【讨论】:

  • @AliSepehri.Kh 编辑:明确说明 Vasfed 的建议。
【解决方案2】:

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

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

试试

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

还有一个“硬编码”方式:proxy_set_header Host post.subdomain.me;

【讨论】:

  • 已编辑以将 $http_host 替换为 $host 或硬编码域
  • 您是否删除了proxy_set_header location / 部分中的主机?
  • 我真的很抱歉,你是对的。我更改了错误的文件。
猜你喜欢
  • 2017-07-25
  • 1970-01-01
  • 2019-04-07
  • 1970-01-01
  • 1970-01-01
  • 2021-02-08
  • 2020-08-15
  • 2020-10-09
  • 2022-07-06
相关资源
最近更新 更多