Rails 4 Static Public index.html

2019-04-04 10:12发布

问题:

Sorry about the simple question, but I can't find the proper fix anywhere.

I used to have a Rails 3.x app running with a simple landing page on public/index.html. Of course, when I updated to Rails 4, my index page is no longer showing. Is there any way to get that feature back?

I know I can create a welcome#index controller/route and render the index.html as a response. But that goes to a different folder, without all the image and css assets that were on public, rendering the former static page.

Any tips?

回答1:

You need to use a controller, but can simply point it to your existing file.

e.g. in routes.rb

root :to => 'welcome#index'

And then in the Welcome controller:

def index
  render :file => 'public/index.html'
end

Alternatively, you could set up Apache to serve that file itself. Seems easier to let Rails do it though!



回答2:

Placing a public/index.html and removing the root directive from config/routes.rb works for me.

$ rails --version
$ Rails 4.2.0


回答3:

A problem with just adding public/index.html is that the index page may not render unless a root path of / is present.

For example, if the app is hosted in a sub-uri, 'http://example.com/my-app/' will hit index.html, but 'http://example.com/my-app' (no trailing /) may not. This could probably be fixed in the configuration of the web server, but if you don't have control of that, you can fix this in routes with:

root to: redirect('index.html')