在/ public路由到静态html页面
如何路由/foo
在Rails中显示/public/foo.html
?
你可以这样做:
将此添加到您的routes.rb文件中。
match '/foo', :to => redirect('/foo.html')
更新
在Rails 4中,它应该使用“get”而不是“match”:
get '/foo', :to => redirect('/foo.html')
感谢Grant Birchmeier
这可以在不触发redirect的情况下完成。 按照下面的步骤进行操作,以便能够在config/routes.rb
路由静态文件,如下例所示:
# 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
- 创build
config/initializers/static_router.rb
与该答案的结尾处显示的文件的全部内容。 确保您为与应用的Rails版本相关的行切换注释。 - 重新启动应用程序(第一个
bin/spring stop
,以确保应用程序完全重新加载)。 - 开始在你的
config/routes.rb
使用static(path)
方法。
# File: config/initializers/static_router.rb module ActionDispatch module Routing class StaticResponder < Endpoint attr_accessor :path, :file_handler def initialize(path) self.path = path # Only if you're on Rails 5+: self.file_handler = ActionDispatch::FileHandler.new( Rails.configuration.paths["public"].first ) # Only if you're on Rails 4.2: # self.file_handler = ActionDispatch::FileHandler.new( # Rails.configuration.paths["public"].first, # Rails.configuration.static_cache_control # ) end def call(env) env["PATH_INFO"] = @file_handler.match?(path) @file_handler.call(env) end def inspect "static('#{path}')" end end class Mapper def static(path) StaticResponder.new(path) end end end end
来源: https : //github.com/eliotsykes/rails-static-router