8

For example, if I'd like to serve a file as application/json or application/rss+xml

I see in the RSS Feed documentation that it mentions saving a file with .rss will auto-detect and serve the correct mime-type.

However, how is this detected? Is there a set list that the CMS uses based on the extension or is it derived from the server in some way?

  • I believe the server just lets Craft know what response headers to send based on the file it's rendering. I'd put that as an answer but I am not positive, also not sure how to set it with twig nor having much luck finding documentation on that, which leads me to think you can't. I know using a .json file did set the proper content-type for json for me. – Bill Criswell Jun 15 '14 at 1:55
17

If you want to explicitly set the mime type from your template, you can do it with Craft's {% header %} tag:

{% header "Content-Type: application/json" %}

If it is already set via this method, Craft will go with it and not attempt to auto-detect/set the mime-type on it's own.

  • You now have access to moderator tools. – nicael Jun 16 '14 at 12:21
  • 2
    Lindsey totally has the better answer though :) – Brandon Kelly Jun 16 '14 at 12:53
  • Lol, thanks Brandon! My answer is more relevant to "how does Craft automatically determine the mime type", whereas yours is more relevant to "how can I manually set the mime type"... Since the original title of this question was a little more ambiguous, I think we both gave solid answers! :) – Lindsey D Jun 16 '14 at 17:49
  • I think it's good to have both answers since you can both manually set the type and Craft will auto-detect (as a fallback) and yes definitely both solid answers! – Kara Jun 18 '14 at 2:51
9

The mime type is automatically determined based on the file extension.

There is nothing within Craft which determines the mime type. Detection follows normal server standards, looking at the file extension to figure it out.

Update:

After a little digging, it appears that Craft relies on the Yii CFileHelper class to determine the mime type of a file. Reading through the Yii docs gives the impression that several techniques are used to figure out the mime type (including looking at the file extension).

Bottom line... Give your file the right extension, and it will be served up with the correct mime type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for?Browse other questions tagged or ask your own question.