Kirill Salykin
Kirill Salykin

Reputation: 711

Serve static html page with nginx based on rails server response

I have 2 html files in /var/files: host1.html and host2.html. I want nginx serving any of them (as index file) depending on rails response, eg http://localhost - should render host1.html or host2.html.

This is Rails controller:

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

And nginx config:

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/;
  }
}

This is not working.

If remove internal - request proxied to Rails, but no internal redirect occurs...

Also, i want to serve not only html files - any actually.

Please advice. Thanks.

Upvotes: 1

Views: 369

Answers (1)

Alexey Ten
Alexey Ten

Reputation: 14364

I would use something like this

nginx config:

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 controller:

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

Here we define “virtual” folder /internal/ that will serve static files. When Rails “redirects” to /internal/host1.html nginx will match it to location /internal/, replace /internal/ with /var/files/ (see alias for details) and serve static file /var/files/host1.html. But if user points his browser to /internal/host1.html he will get 404 error due to internal directive.

Upvotes: 3

Related Questions