Routing to static html page in /public

59,416

Solution 1

You can do this:

Add this, into your routes.rb file.

match '/foo', :to => redirect('/foo.html')

Update

In Rails 4, it should use "get", not "match":

get '/foo', :to => redirect('/foo.html')

thanks Grant Birchmeier

Solution 2

This can be done without triggering a redirect. Follow the steps further down to be able to route static files in config/routes.rb as shown in this example:

# This route will serve public/index.html at the /login URL 
# path, and have a URL helper named `login_path`:
get "/login", to: static("index.html")

# This route will serve public/register.html at the /register
# URL path, and have URL helper named `new_user_registration_path`:
get "/register", to: static("register.html"), as: :new_user_registration
  1. Install the rails-static-router gem: https://github.com/mufid/rails-static-router#installation
  2. Restart app (first bin/spring stop to be sure app is completely reloaded).
  3. Start using the static(path) method in your config/routes.rb.
Share:
59,416
Aen Tan
Author by

Aen Tan

Aenism.com

Updated on July 05, 2022

Comments

  • Aen Tan
    Aen Tan about 2 years

    How can I route /foo to display /public/foo.html in Rails?

  • bendytree
    bendytree almost 13 years
    If you're redirecting to an asset in public, you probably want redirect('/foo.html') (without the /public)
  • Grant Birchmeier
    Grant Birchmeier almost 11 years
    In Rails 4, it should be get '/foo', :to => redirect('/foo.html') ("get" instead of "match").
  • Emily
    Emily almost 11 years
    Is there a way to do this where it sends the content of the file rather than redirecting?
  • Arkan
    Arkan almost 11 years
    @Emily I would recommend you to use a controller to send the content of a file.See this link: apidock.com/rails/ActionController/Streaming/send_file . However, something like this should work. match "/foo", :to => proc {|env| [200, {}, [File.open(Rails.root.join('config', 'routes.rb')).read]] }, via: :get
  • matanster
    matanster over 10 years
    Deploying to Heroku, this yields a redirect loop. Perplexing it's that complex to get a landing page to work in rails....
  • Abhinay
    Abhinay over 8 years
    @Arkan +1 for mentioning the name of Grant.
  • xaphod
    xaphod over 7 years
    @Arkan +1 for a method that works well for domain control validation (DCV) on Heroku when applying for new SSL cert
  • waza
    waza over 7 years
    Just in case someone trying to use this for Rails 5, the syntax must be changed. Omit the second parameter, so it should be only ActionDispatch::FileHandler.new(Rails.configuration.paths["p‌​ublic"].first)
  • guzart
    guzart over 7 years
  • Hued Bafuli
    Hued Bafuli over 6 years
    Don't ask me why, but this blew up for me in production unless I have require 'action_dispatch/middleware/static' at the top...