2011-04-12 44 views
57

如何路由/foo以在Rails中显示/public/foo.html路由到/ public中的静态html页面

+0

可能是重复的:http://stackoverflow.com/questions/1146624/how-to-do-static-content-in-rails – 2011-04-12 06:36:58

+4

赛义德,这不是一个愚蠢的问题,因为该问题是指维护布局等等 – 2012-02-12 04:41:36

+0

就像一个笔记一样,如果你想设置一个静态的欢迎页面或者其他东西,rails会自动显示'public/index.html'。 – 0112 2017-12-01 03:35:51

回答

87

您可以这样做:

将此添加到您的routes.rb文件中。

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

更新

在Rails 4,它应该使用 “搞定”,而不是 “匹配”:Grant Birchmeier

+2

如果你公开重定向到资产,你可能想'重定向('/ foo.html')'(不含/ public) – bendytree 2011-08-17 20:54:51

+0

固定重定向路径 – 2012-07-17 17:33:15

+4

不适用于Rails 3.2.8 – antiqe 2012-08-31 10:13:45

4

这可以在不触发完成

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

感谢重定向。按照以下步骤进一步下降到能够在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 
  1. 创建config/initializers/static_router.rb与这个答案的末尾显示文件的全部内容。确保您为与应用的Rails版本相关的行切换注释。
  2. 重新启动应用程序(首先bin/spring stop以确保应用程序完全重新加载)。
  3. 开始在您的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

+2

仅当有人试图使用Rails 5时,必须更改语法。省略第二个参数,所以它应该只是'ActionDispatch :: FileHandler.new(Rails.configuration.paths [“public”]。第一个)' – waza 2017-04-04 04:38:57

+0

链接到[ActionDispath :: FileHandler](https://github.com/ rails/rails/blob/ffa13e9d4fdd0684844ad72000c6e949d565dd35/actionpack/lib/action_dispatch/middleware/static.rb#L16)并链接到[Redirect guzart 2017-04-04 06:16:09

+1

不要问我为什么,但是这会在我制作的时候炸毁我,除非我在顶部有'require'action_dispatch/middleware/static'' ... – dain 2017-10-17 20:14:57

0

例如,在轨道4添加以下路由:

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

你也需要从 '公共' 目录启用静态文件的配置:

config.serve_static_files = true 

OR

config.serve_static_assets = true 

你也可能需要提供您的公共目录中NGINX配置根。