如何使用sinatra创建通配符重定向

时间:2012-11-09 11:15:35

标签: heroku sinatra

我最近在Heroku上升级到新的雪松堆时遇到了问题。所以我通过将我的旧网站转储到由下面的sinatra代码驱动的静态公共文件夹来解决这个问题。

但是,指向旧网址的链接不会加载静态网页,因为它们无法将.html附加到网址的末尾。

require 'rubygems'
require 'sinatra'

set :public, Proc.new { File.join(root, "public") }

before do
  response.headers['Cache-Control'] = 'public, max-age=100' # 5 mins
end

get '/' do
  File.read('public/index.html')
end

如何将.html附加到所有网址的末尾?它会是这样的:

get '/*' do
  redirect ('/*' + '.html')
end

1 个答案:

答案 0 :(得分:2)

您可以通过params[:splat]或帮助request.path_info获取匹配的路径,我倾向于使用第二个:

get '/*' do
  path = params[:splat].first # you've only got one match
  path = "/#{path}.html" unless path.end_with? ".html" # notice the slash here!
  # or
  path = request.path_info
  path = "#{path}.html" unless path.end_with? ".html" # this has the slash already
  # then
  redirect path
end