dehio3’s diary

仕事、生活、趣味のメモ

公開ファイルが文字化ける

事象

  • ブラウザ上にて公開しているファイルの文字が文字化けして表示される。
  • ファイルのOS上の文字コードShift_JIS

環境

OS

# cat /etc/system-release
Amazon Linux AMI release 2017.03

apache

# /usr/sbin/httpd -V
Server version: Apache/2.2.31 (Unix)
Server built:   Jul 19 2016 00:11:31
Server's Module Magic Number: 20051115:40
Server loaded:  APR 1.5.1, APR-Util 1.4.1
Compiled using: APR 1.5.1, APR-Util 1.4.1

ファイルの文字コード

# nkf -guess hoge.txt
Shift_JIS (LF)

OSの文字コード

# cat /etc/sysconfig/i18n
LANG=ja_JP.UTF-8

Response Header の確認

Accept-Ranges:bytes
Content-Length:169
Content-Type:text/plain; charset=UTF-8
Date:Mon, 05 Jun 2017 02:52:32 GMT
ETag:"138-a9-550f427692dc0"
Last-Modified:Fri, 02 Jun 2017 06:20:47 GMT
Server:Apache/2.2.31 (Amazon)

Content-TypecharsetUTF-8に指定されている。

対処

httpd.conf の AddDefaultCharset を無効化

# grep AddDefaultCharset /etc/httpd/conf/httpd.conf
#AddDefaultCharset UTF-8

変更後のResponse Header

Accept-Ranges:bytes
Connection:close
Content-Length:169
Content-Type:text/plain
Date:Mon, 05 Jun 2017 03:00:02 GMT
ETag:"138-a9-550f427692dc0"
Last-Modified:Fri, 02 Jun 2017 06:20:47 GMT
Server:Apache/2.2.31 (Amazon)

charsetの指定が解除され、ブラウザが自動で判定した文字コードで表示された。

AddDefaultCharset とは?

  • レスポンスのコンテントタイプが text/plain あるいは text/html の場合に追加するデフォルトの charset パラメータ

core - Apache HTTP サーバ バージョン 2.2