【问题标题】:Serve static html page with nginx based on rails server response使用基于 Rails 服务器响应的 nginx 提供静态 html 页面
【发布时间】:2015-09-04 03:27:51
【问题描述】:

我在 /var/files 中有 2 个 html 文件:host1.html 和 host2.html。 我希望 nginx 根据 rails 响应为它们中的任何一个提供服务(作为索引文件),例如 http://localhost - 应该呈现 host1.html 或 host2.html。

这是 Rails 控制器:

class HomeController < ApplicationController
  def index
    response.headers['X-Accel-Redirect'] = 'host1.html'
    head :ok
  end
end

和 nginx 配置:

upstream app_server {
  server 0.0.0.0:3000 fail_timeout=0;
}

server {
  listen 8080 default;

  location /{
    proxy_pass http://app_server;
    internal;
    root /var/files/;
  }
}

这不起作用。

如果删除内部 - 请求代理到 Rails,但没有发生内部重定向...

另外,我想提供的不仅仅是 html 文件——实际上是任何文件。

请指教。 谢谢。

【问题讨论】:

  • 我看不到你在哪里通过你的请求 ro rails。此外,X-Accel-Redirect 标头必须以斜杠开头 (/)
  • 它被代理到 0.0.0.0:3000 - rails 服务器在这里运行。
  • > 必须以斜杠 (/) 开头,我都试过了。
  • "它被代理到 0.0.0.0:3000" — 我在你的配置中没有看到这个。显示真实的完整配置
  • @AlexeyTen 更新了,请看。请考虑到我是 nginx 新手。

标签: ruby-on-rails nginx


【解决方案1】:

我会用这样的东西

nginx 配置:

upstream app_server {
  server 0.0.0.0:3000 fail_timeout=0;
}

server {
  listen 8080 default;

  location / {
    proxy_pass http://app_server;
  }

  location /internal/ {
    internal;
    alias /var/files/;
  }
}

Rails 控制器:

class HomeController < ApplicationController
  def index
    response.headers['X-Accel-Redirect'] = '/internal/host1.html'
    head :ok
  end
end

在这里,我们定义了“虚拟”文件夹/internal/,它将提供静态文件。当 Rails “重定向”到 /internal/host1.html 时,nginx 会将其匹配到 location /internal/,将 /internal/ 替换为 /var/files/(详见 alias)并提供静态文件 /var/files/host1.html。但是如果用户将浏览器指向/internal/host1.html,由于internal 指令,他将收到404 错误。

【讨论】:

    猜你喜欢
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-06
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    相关资源
    最近更新 更多