【发布时间】:2014-01-05 20:46:54
【问题描述】:
我在 Heroku (http://tomgillard.herokuapp.com) 上托管了一个 Middleman 博客,并且一直在尝试根据 google 的 PageSpeed 建议对其进行优化。一个建议是我在网站的 HTML 页面上提供一个字符集。
HTML 页面在
中包含 html5 但这似乎还不够,我认为我可以将其设置为服务器端。这是我的 config.ru
require 'rack/contrib'
# Modified version of TryStatic, from rack-contrib
# https://github.com/rack/rack-contrib/blob/master/lib/rack/contrib/try_static.rb
# Serve static files under a `build` directory:
# - `/` will try to serve your `build/index.html` file
# - `/foo` will try to serve `build/foo` or `build/foo.html` in that order
# - missing files will try to serve build/404.html or a tiny default 404 page
module Rack
class TryStatic
def initialize(app, options)
@app = app
@try = ['', *options.delete(:try)]
@static = ::Rack::Static.new(lambda { [404, {}, []] }, options)
end
def call(env)
orig_path = env['PATH_INFO']
found = nil
@try.each do |path|
resp = @static.call(env.merge!({'PATH_INFO' => orig_path + path}))
break if 404 != resp[0] && found = resp
end
found or @app.call(env.merge!('PATH_INFO' => orig_path))
end
end
end
# Serve GZip files to browsers that support them
use Rack::Deflater
# Custom HTTP Headers
use Rack::ResponseHeaders do |headers|
headers['Charset'] = 'UTF-8'
end
#Custom Cache Expiry
use Rack::StaticCache, :urls => ["/img", "/css", "/js", "/fonts"], :root => "build"
# Attempt to serve static HTML file
use Rack::TryStatic, :root => "build", :urls => %w[/], :try => ['.html', 'index.html', '/index.html']
# Serve 404 messages:
run lambda{ |env|
not_found_page = File.expand_path("../build/404.html", __FILE__)
if File.exist?(not_found_page)
[ 404, { 'Content-Type' => 'text/html', 'Charset' => 'UTF-8' }, [File.read(not_found_page)] ]
else
[ 404, { 'Content-Type' => 'text/html', 'Charset' => 'UTF-8' }, ['404 - page not found'] ]
end
}
我认为我可以使用 rack-contrib 中的 Rack::ResponseHeaders 但我认为我没有正确使用它;
# Custom HTTP Headers
use Rack::ResponseHeaders do |headers|
headers['Charset'] = 'UTF-8'
end
就像我说的,我从高处和低处搜索过;参考文档(Rack、heroku)、SO 问题、博客文章、github,应有尽有。
非常感谢任何帮助。
干杯, 汤姆
【问题讨论】:
-
“但这似乎还不够”是什么意思?您是否只是在寻找要设置的标头 - 它应该是
Content-Type: text/html; charset=utf-8(即标头名称是Content-Type,值是text/html; charset=utf-8)。见w3.org/International/O-HTTP-charset。 -
谢谢@matt。是的,看起来我已将标题设置为不存在的标题(字符集)。如果我将 headers['Charset] = 'utf-8' 更改为 headers['Content-type'] = 'text/html; charset=utf-8' 将 Rack 知道仅将该内容类型应用于 html 文件,还是会在服务器上的每个文件中设置它?如果是后者,我如何只设置带有您上面提到的标题 tpye 和值的 .html 文件?这是我不确定的。
标签: ruby heroku utf-8 rack middleman