Integration by me

Then you will know the truth, and the truth will set you free.

How to set charset of all text responses on nginx

It’s usual that all text files on a site share the same character encoding. Especially UTF-8 is modern de facto standard. However, the default charset_types does not contain text/css, let alone other non-plain text types e.g. text/markdown.

The default charset_types should be text/* because most of them are parsed in ASCII (us-ascii) by default for backward compatibility. A text/xml response is parsed in ASCII even if BOM and XML declaration tells otherwise. Therefore, we should really use application/xml for XML responses now.

Nevertheless, the charset_types setting checks complete matches only, or we have to resort to the universal match (*). Luckily, nginx has map powered with regex and charset_types accepts a variable.

map $sent_http_content_type $charset {
    ~^text/   utf-8;
}

charset       $charset;
charset_types *;

This setting would make nginx specify UTF-8 for all text responses, e.g. text/css; charset=utf-8.

Author: Chen-Pang He

I’m Chen-Pang He (何震邦), studying medicine in Taipei Medical University. I’m a programmer skilled in calculus and linear algebra. See the for more details.

Chen-Pang He
Uncategorized