如何与Sinatra建立通配符重定向



我最近遇到了升级到Heroku上新的Cedar堆栈的问题。因此,我通过将旧网站倾倒到下面的Sinatra代码为动力的静态公共文件夹中进行了处理。

但是,链接到旧URL不会加载静态页面,因为它们无法将.html附加到URL的末端。

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附加到所有URL的末尾?会这样:

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

您可以通过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

最新更新