2012-08-06 94 views
3

让我的应用程序在Heroku上运行。使用rack-canonical-host来处理从myapp.heroku.com到规范域的重定向。我的域名注册商处理来自根域的重定向。重新指引网址以在Sinatra中添加尾部斜线

我使用Octopress(基于哲基尔框架;西纳特拉运行下方),然后我想重新定向所有的URL 没有尾随斜线尾随斜线变型。我会在网络服务器端执行此操作,但我无法使用Heroku进行此操作。

我还假设301重定向是执行重定向的最佳实践。

我确实看过了Sinatra文档,但它似乎默认情况下是“?”选项。在你的路线上,但是我的路线没有这个语法,但仍然处理有和没有案件。

这是我目前config.ru

require 'bundler/setup' 
require 'sinatra/base' 
require 'rack/contrib' 
require 'rack-canonical-host' 

# The project root directory 
$root = ::File.dirname(__FILE__) 

class SinatraStaticServer < Sinatra::Base 

    get(/.+/) do 
    expires 3600, :public, :must_revalidate 
    send_sinatra_file(request.path) {404} 
    end 

    not_found do 
    expires 0, :public, :no_cache 
    send_sinatra_file('404.html') {"Sorry, I cannot find #{request.path}"} 
    end 

    def send_sinatra_file(path, &missing_file_block) 
    file_path = File.join(File.dirname(__FILE__), 'public', path) 
    file_path = File.join(file_path, 'index.html') unless file_path =~ /\.[a-z]+$/i 
    File.exist?(file_path) ? send_file(file_path) : missing_file_block.call 
    end 

end 

if ENV['CANONICAL_HOST'] 
    use Rack::CanonicalHost, ENV['CANONICAL_HOST'], ignore: ['media.eatsleeprepeat.net', 'static.eatsleeprepeat.net'] 
end 

use Rack::Deflater 

run SinatraStaticServer 

回答

3

这对我的作品添加结尾的斜杠到不使用重定向有一个任何路线:

get %r{(/.*[^\/])$} do 
    redirect "#{params[:captures].first}/" 
end 

get %r{/.*/$} do 
    "successful redirect for '#{request.path}'" 
end 
+0

完美。只需要第一个区块。本地测试和'/ 2012/blog-post-title'干净地重定向到'/ 2012/blog-post-title /' – elithrar 2012-08-13 11:39:01

2

不要对你有一个完整的答案,但我用重定向沿线你的建议如

get '/blog/2012/05/01/delegation/?' do 
    redirect '/blog/2012/05/01/effective-delegation/', 301 
end 

我觉得对于类,octopress假设类别/ index.html的,因此:

file_path = File.join(file_path, 'index.html') unless file_path =~ /\.[a-z]+$/i 

线,这将转化domain.com/category到domain.com/category/index.html 。我相信为什么你的一些URL有或没有结尾的斜杠继续工作。

希望这有助于有点...