How to Setup Urls for Static Site with Ruby Rack on Heroku

How to setup URLs for static site with Ruby Rack on Heroku

For now I found the best answer to be:

use Rack::Static, 
:urls => ["/media/images", "/media/js", "/media/css"],
:root => "public"

map "/" do
run lambda { |env|
[
200,
{
'Content-Type' => 'text/html',
'Cache-Control' => 'public, max-age=86400'
},
File.open('public/index.html', File::RDONLY)
]
}
end

map "/portfolio" do
run lambda { |env|
[
200,
{
'Content-Type' => 'text/html',
'Cache-Control' => 'public, max-age=86400'
},
File.open('public/portfolio/index.html', File::RDONLY)
]
}
end

And map every URL to its respective file. Tedious, but works. See also the answer to this question regarding URL variables. Couldn't get it to work for me though.

Ruby Rack Heroku: No CSS styling when serving a static site

Set config.serve_static_assets = true in config/production.rb. You can alternatively add Heroku's rails_12factor gem which does this for you, among other things.

Serve files using Rack TryStatic directly?

As you’ve noticed, a Rack middleware component such as Rack::TryStatic needs another app to pass requests onto. You could create a simple one to use that for example just returned a 404 response, such as:

app = lambda {|env| [404, {'Content-type' => 'text/plain'}, ['Not found']
run Rack::TryStatic.new app, :root => "build", :urls => %w[/], :try => ['.html']

or equivalently:

use Rack::TryStatic, :root => "build", :urls => %w[/], :try => ['.html']
run lambda {|env| [404, {'Content-type' => 'text/plain'}, ['Not found']]}

If you have your own 404 file, you could use rack-contrib’s Rack::NotFound instead of a custom end point of your own:

use Rack::TryStatic, :root => "build", :urls => %w[/], :try => ['.html']
run Rack::NotFound.new('path/to/your/404.html')

If you weren’t using the :try array of file extensions to try and serve, you could use Rack::File directly. Internally, Rack::TryStatic uses Rack::Static, which in turn uses Rack::File. Unlike TryStatic and Static, Rack::File is a Rack application in its own right, and so doesn’t need a separate app to pass requests to. Your config.ru would then simply be:

run Rack::File.new './build'

although this wouldn’t allow for “bare” requests to be served with the corresponding .html file — all requests would need to specify the whole file name.



Related Topics



Leave a reply



Submit