Rails 3 web font (woff) mime type

2020-07-10 07:55发布

问题:

We serve some web fonts (.woff) from our static assets and I would like to set the correct mime type (application/x-font-woff). I tried to do this in config/initializers/mime_types.rb but it had no effect:

Mime::Type.register "application/x-font-woff", :woff

The returned mime type still stayed application/octet-stream. I even tried to add this line (because it was the only other place in the rails source where I could find the string "woff"):

Rack::Mime::MIME_TYPES[".woff"] = "application/x-font-woff"

But it still didn't help. How do I properly set the mime type for web fonts?

回答1:

Until Rack fixes its MIME-type list to a correct woff, the interim hack is indeed your config/initializers/mime_types.rb line:

# tell Rack (and Sprockets) about modern font MIME types:
Rack::Mime::MIME_TYPES['.woff'] = 'application/x-font-woff'

To have it actually take effect, though, you have to wipe tmp/cache and restart your server.



回答2:

While I also didn't figure out some hack solution to it, I researched this a few days ago (on my rails 3.2 dev server running WEBRick, for reference), and it's Sprockets that sets the bad MIME type on the response, maybe by delegating the choice to Rack, which has a dumb notion of what MIME type to pass for fonts (as of this ravinggenious commit).

I filed a (detailed) ticket on Sprockets and a pull request on Rack, hoping it'd get fixed upstream where it makes the most sense instead, but neither has seen much action yet. I probably should have paid more attention to ttf and eof too, but it was late and I didn't think of it at the time.

(Commenting on either might raise awareness of the problem – one issue is no issue, a people pile is a problem worth fixing? :-)