使用不区分大小写的URL提供来自Sinatra的静态文件

时间:2012-02-05 01:51:51

标签: ruby sinatra rack

我正在使用瘦网络服务器和基本的Sinatra应用程序在Heroku上为静态站点(由Jekyll / Octopress生成)提供服务。我的目标是支持不区分大小写的URL(通过从不同大小写的URL或重定向/重写的URL提供相同的页面)。

E.g。 http:/mysite/Hello.htmlhttp://mysite/hello.html都应该提供相同的文件。

这是config.ru(来自Octopress distrib):

require 'bundler/setup'
require 'sinatra/base'
require 'rack'
require 'rack/rewrite'

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

class SinatraStaticServer < Sinatra::Base  

  get(/.+/) do
    send_sinatra_file(request.path) {404}
  end

  not_found do
    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

run SinatraStaticServer

使用Rack或Sinatra有没有办法做到这一点?到目前为止,我所获得的最远的是在.downcase中使用send_sinatra_file来封装所有文件。

1 个答案:

答案 0 :(得分:0)

以下是您的路线选择:

get '/' do
  send_file(File.join(File.dirname(__FILE__), 'public', 'index.html'))
end

get '*' do
  file_path = File.join(File.dirname(__FILE__), 'public',  request.path.downcase)
  File.exist?(file_path) ? send_file(file_path) : halt 404
end

not_found do
  send_file(File.join(File.dirname(__FILE__), 'public', '404.html'))
end

这是未经测试的,因为无论如何我可能无法重现您的环境。但我认为它可以用于您的目的,假设您的所有页面都是小写的(正如您所提到的)并且您还有一个实际的404.html页面。

相关问题