- 目标:发现并批量修复因编码不当导致的乱码(常见为 GBK/GB2312 -> UTF-8 问题)。
- 先决条件:SSH 访问、root 或文件所有者权限,安装工具:iconv、file、uchardet(或 python chardet)、enca、dos2unix、parallel(可选)。
- 安装示例(Debian/Ubuntu):sudo apt update && sudo apt install -y file iconv uchardet enca dos2unix parallel
- 步骤1:用 curl 查看 Content-Type:curl -sI https://example.com | grep -i Content-Type。
- 步骤2:若没有 charset,前端可能靠文件实际编码,或服务器未设置 header。记录需要检查的 URL 列表到 urls.txt。
- 在站点根目录执行:find /var/www/html -type f -name '*.html' -o -name '*.php' | while read f; do file -i "$f"; done。
- 推荐用 uchardet 自动识别:uchardet "$f" 返回编码。结合 find 可批量识别并输出到 report.txt:find . -type f -name '*.html' -print0 | xargs -0 -I{} sh -c 'echo "{}: $(uchardet "{}")"' > report.txt
- 先备份:cp page.html page.html.bak。
- 检测:uchardet page.html(或 python -c "import chardet;...")。
- 转码示例:iconv -f GB18030 -t UTF-8 page.html > page.utf8.html && mv page.utf8.html page.html。确认浏览器显示正常并且 HTTP header 指定 charset=UTF-8。
- 脚本要点:检测、备份、转码、替换、记录日志。示例脚本片段:
for f in $(find /var/www/html -type f -name '*.html'); do enc=$(uchardet "$f"); if [ "$enc" != "UTF-8" ]; then cp "$f" "$f.bak"; iconv -f "$enc" -t UTF-8 "$f.bak" -o "$f" && echo "$f converted from $enc" >> convert.log; fi; done
- 并行化:用 GNU parallel 加快:find ... | parallel -j8 '处理命令'
- MySQL:检查连接字符集与表/列的字符集,ALTER TABLE ... CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci。
- PHP/应用:确保 header('Content-Type: text/html; charset=utf-8') 与 PDO/MySQLi 的 set names 或 charset 参数一致。
答:用脚本批量请求 URL 列表并检测 body 编码与头。示例:while read url; do hdr=$(curl -sI "$url" | grep -i Content-Type); body=$(curl -s "$url"); echo "$body" | uchardet - # uchardet 可检测 stdin 编码; 比较 header 与实际编码,不一致则记录。done
答:不会只要在脚本中过滤文件类型(只处理 .html/.php/.css/.js/.txt 等文本),并在转换前用 file 命令或 mime-type 判断。始终先备份并在小范围测试后再大规模运行。
答:1) 备份全站;2) 扫描并生成编码报告;3) 在测试环境按脚本批量转码并验证;4) 修正服务器 header 与数据库字符集;5) 部署并监控日志(convert.log),按需回滚。