在 Heroku 上安装我的应用程序。使用rack-canonical-host处理从 myapp.heroku.com 到规范域的重定向。我的域注册商处理来自根域的重定向。
我正在使用 Octopress(一个基于 Jekyll 的框架;Sinatra 在其下运行)并且我想重定向所有 URL 的没有尾部斜杠变体。 我会在 Web 服务器端执行此操作,但我无法使用 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
最佳答案
这对我来说适用于向任何没有使用重定向的路由添加尾部斜杠:
get %r{(/.*[^\/])$} do
redirect "#{params[:captures].first}/"
end
get %r{/.*/$} do
"successful redirect for '#{request.path}'"
end
关于heroku - 重定向 URL 以在 Sinatra 中添加尾部斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11821621/