首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

CentOS Apache 默認 UTF-8 導致 GBK 頁面亂碼的解決方法

     編輯:PHP 相關知識

問題現象

CentOS 下 Apache 默認配置 AddDefaultCharset UTF-8,導致無 meta charset 聲明的 GBK/GB2312 頁面顯示亂碼。

解決方案:修改 httpd.conf

  1. 編輯配置文件:
    vi /etc/httpd/conf/httpd.conf
  2. 搜尋 AddDefaultCharset:
    AddDefaultCharset UTF-8
  3. 修改為關閉或指定 GBK:
    方案 A(推薦):關閉默認編碼,由頁面 meta 控制
    AddDefaultCharset Off
    方案 B:強制默認 GB2312
    AddDefaultCharset GB2312
  4. 重啟 Apache:
    systemctl restart httpd 或 service httpd restart

方案對比與建議

方案優點缺點適用場景
Off完全由頁面控制,兼容 UTF-8/GBK 混合站點頁面必須正確設置 meta charset現代項目、多編碼共存
GB2312舊項目零改動即可正常顯示UTF-8 頁面會被強制誤判為 GBK 導致亂碼純 GBK 老舊系統、無法修改頁面代碼

最佳實踐:頁面級編碼聲明(無論 Apache 設置)

<?php
// PHP 輸出頭(最優先,覆蓋 Apache)
header('Content-Type: text/html; charset=gb2312'); // 或 utf-8
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
...

驗證方法

curl -I https://yourdomain.com/gbk-page.php
# 檢查響應頭 Content-Type 是否包含 charset=gb2312
# 或無 charset (AddDefaultCharset Off 時)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved