2012-11-09 44 views
0

我最近在升級到Heroku上的新雪松堆棧時遇到問題。所以我通過將我的舊網站轉儲到由下面的sinatra代碼提供支持的靜態公用文件夾中來解決它。如何使用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 

回答

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 
+0

太好了!作品一種享受!非常感謝。 – user251732