【问题标题】:Routing to static html page in /public路由到 /public 中的静态 html 页面
【发布时间】:2011-08-03 14:54:07
【问题描述】:

如何在 Rails 中路由 /foo 以显示 /public/foo.html

【问题讨论】:

  • 赛义德,这不是那个问题的骗局,因为那个问题是指维护布局等。
  • 请注意,如果您尝试设置静态欢迎页面或其他内容,如果未指定其他内容,rails 将自动显示public/index.html

标签: ruby-on-rails ruby-on-rails-3 url routing


【解决方案1】:

你可以这样做:

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

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

更新

在 Rails 4 中,它应该使用“get”,而不是“match”:

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

感谢Grant Birchmeier

【讨论】:

  • 如果您要重定向到公开的资产,您可能需要redirect('/foo.html')(没有/public)
  • 在 Rails 4 中,它应该是get '/foo', :to => redirect('/foo.html')(“get”而不是“match”)。
  • 有没有办法做到这一点,它发送文件的内容而不是重定向?
  • @Emily 我建议您使用控制器来发送文件的内容。请参阅此链接:apidock.com/rails/ActionController/Streaming/send_file。但是,这样的事情应该有效。匹配 "/foo", :to => proc {|env| [200, {}, [File.open(Rails.root.join('config', 'routes.rb')).read]] },通过::get
  • 部署到 Heroku,这会产生一个重定向循环。让登录页面在 Rails 中工作是如此复杂,令人困惑......
【解决方案2】:

这可以在不触发重定向的情况下完成。按照下面的步骤,可以在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. 安装 rails-static-router gem:https://github.com/mufid/rails-static-router#installation
  2. 重新启动应用(首先bin/spring stop 以确保应用完全重新加载)。
  3. 开始在您的config/routes.rb 中使用static(path) 方法。

【讨论】:

  • 万一有人试图将它用于 Rails 5,必须更改语法。省略第二个参数,所以应该只有ActionDispatch::FileHandler.new(Rails.configuration.paths["public"].first)
  • 不要问我为什么,但这在生产中对我来说很糟糕,除非我在顶部有 require 'action_dispatch/middleware/static'...
【解决方案3】:

例如在 Rails 4 中添加以下路由:

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

您还需要在配置中启用“公共”目录中的静态文件:

config.serve_static_files = true

config.serve_static_assets = true

此外,您可能需要在 NGINX 配置中以 root 身份提供您的公共目录。

【讨论】:

    猜你喜欢
    • 2015-02-24
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-07
    • 2019-06-05
    • 2014-10-13
    • 1970-01-01
    相关资源
    最近更新 更多