CentOS 下 Apache 出现乱码,通常是字符集配置不一致导致的。下面按常见原因逐步排查和修复。
先确认你的网页文件编码是 UTF-8(推荐):
file -i index.html
如果不是 UTF-8:
iconv -f GBK -t UTF-8 index.html > index.utf8.html
mv index.utf8.html index.html
vi /etc/httpd/conf/httpd.conf
添加或修改:
AddDefaultCharset UTF-8
如果已有但被注释,取消注释。
CentOS 常在:
/etc/httpd/conf.d/
查看是否有:
AddDefaultCharset OFF
如果有,改为:
AddDefaultCharset UTF-8
如果你用了 vhost:
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/html
AddDefaultCharset UTF-8
</VirtualHost>
在 php.ini 中设置:
vi /etc/php.ini
default_charset = "UTF-8"
PHP 文件开头也可加:
header("Content-Type:text/html; charset=utf-8");
HTML 文件 head 中必须有:
<meta charset="UTF-8">
或老写法:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
如果是从数据库读出的乱码:
SET NAMES utf8;
并确保:
utf8 / utf8mb4systemctl restart httpd
清缓存或用 Ctrl+F5 强制刷新。
AddDefaultCharset UTF-8default_charset如果你愿意,可以告诉我:
我可以给你更精确的配置。