Chris Zetter

Setting headers in Rails 4

The new default headers setting that has been added to rails 4 makes it really easy to set HTTP headers across your app.

How to use

In your application.rb file, or in a specific environment you add to the hash of default headers that Rails adds to every response:

config.action_dispatch.default_headers.merge!('X-UA-Compatible' => 'IE=edge')

Out of the box, config.action_dispatch.default_headers contains a set of headers useful for preventing cross site scripting attacks so it’s important to merge any changes into the existing set rather than replace them.

If you restart your app and do a curl -I <appname> and you’ll see the header is now included.

HTTP/1.1 200 OK
X-UA-Compatible: IE=edge

What it means

One use for default headers is setting the X-UA-Compatible header which signals to older versions of Internet Explorer not to use compatibility mode. This is what the now removed ActionDispatch::BestStandardsSupport middleware used to do in Rails 3.

If you look at the source in Action Dispatch you can see any other headers provided will overwrite the default ones which means that you can override headers in certain controllers if you wanted to:

response.headers["X-UA-Compatible"] = "IE=9"

This post was updated on 2014-09-25 to highlight that you probably want to merge in your new headers to keep the initial set that Rails provides.

Read more by me, follow me on Mastodon or subscribe.