我有一个Middleman博客托管在Heroku(http://tomgillard.herokuapp.com),并一直试图根据谷歌的PageSpeed建议对其进行优化。一个建议是我在网站的HTML页面上提供一个字符集。在中间人博客网站的HTML页面上设置字符集为UTF-8
HTML页面包含HTML5 <元的charset =“UTF-8” >在<头>但这似乎并没有足够的操作系统,我想我可以将它设置服务器端。
这里是我的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
}
我想我可以用机架::从机柜的contrib responseHeaders响应,但我正确使用它,我不认为;
# Custom HTTP Headers
use Rack::ResponseHeaders do |headers|
headers['Charset'] = 'UTF-8'
end
就像我说过的,我搜索了高和低;咨询文档(Rack,Herku),SO问题,博客帖子,github,你的名字。
任何帮助,这是非常赞赏。
干杯, 汤姆
你是什么意思,但这似乎不够“?你只是想要设置哪个头 - 它应该是'Content-Type:text/html; charset = utf-8“(即头部名称为”Content-Type“,值为”text/html; charset = utf-8“)。见http://www.w3.org/International/O-HTTP-charset。 – matt
谢谢@matt。是的,它看起来像我已经设置标题不存在(字符集)。 如果我将标题['Charset] ='utf-8'改为标题['Content-type'] ='text/html; charset = utf-8'将Rack知道仅将该内容类型应用于html文件,还是将其设置为跨服务器上的每个文件?如果是后者,我如何只设置.html文件头部tpye和你上面提到的值?这是我不确定的。 –