54

What is the right way to enable correct charset headers in NGINX?

I'm analyzing my website with Google Page Speed. It says that I should specify the charset of HTML files in HTTP-headers. What is the right way to do this?

I already tried to set charset utf-8; in the server {} declaration of my NGINX configuration file, but it hasn't got any effect.

My server responds with the following header:

Connection: keep-alive
Date: Fri, 16 Sep 2011 12:43:24 GMT
Last-Modified: Fri, 02 Sep 2011 15:13:17 GMT
Server: nginx/0.7.67

Thank you.

2

4 Answers 4

48

Adding charset utf-8; is pretty much everything you need to do. Are sure that you didn't forget to reload nginx after you changed the configuration file?

Besides at the moment of writing, curl -I https://vorb.de/ returns the following result:

HTTP/1.1 200 OK
Server: nginx/0.7.67
Date: Fri, 16 Sep 2011 13:20:03 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 1705
Last-Modified: Fri, 02 Sep 2011 15:13:17 GMT
Connection: keep-alive
Vary: Accept-Encoding
Accept-Ranges: bytes

So everything looks ok now.

29

Setting the charset might not work if you do not set "charset_types" directive which you want UTF-8.

For example: When you set "charset utf-8;", all HTML will reflect, but not JSON files, because they are not set by default on "charset_types".

http://nginx.org/en/docs/http/ngx_http_charset_module.html#charset_types

0
7

This is all you need.

charset utf-8;
source_charset utf-8;

It won't work for me unless I have both.

2
  • @giacomo1968, don't edit the grammar in my answer just so you can get points or something. Dec 28, 2022 at 18:33
  • “…don't edit the grammar in my answer just so you can get points or something…” I didn’t edit your grammar to “get points or something.” I edited your grammar to improve your answer. I didn’t change the content of your answer for any reason but to improve very basic formatting and text. If you actually look at the edits you can see I barely changed anything. But if you don’t like it, you are free to roll back the edits. The Stack Exchange sites allow community members to edit any question/answer to improve it. And you can always it roll back. Dec 28, 2022 at 18:36
6

You might have to also adjust the charset_types setting to include the mime type you want to set the charset setting for (e.g. text/calendar is not included there by default).

For what it's worth I think that text/* should be handled by default - but you cannot use it here (as with Apache IIRC).

See http://nginx.org/en/docs/http/ngx_http_charset_module.html#charset_types

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .