Nginx根据不同浏览器语言配置跳转

实现根据用户浏览器使用的语言自动判断跳转到对应的语言界面

简体和繁体判断 根据HTTP首部的 Accept-Language 决定提供简体或繁体的文件。在Chrome中, chrome://settings/languages 可以设定偏好语言,浏览器会据此设置 Accept-Language 首部。较好的处理方式是解析该字段,获取qvalue,根据优先级选取最恰当的语言。但仅用于支持简繁体,我想用取巧的办法:忽略优先级,只要 Accept-Language 里出现了 zh-Hant 、 zh-TW 、 zh-HK 等字样,就返回繁体,否则返回简体。

map $http_accept_language $lang {
 default zhs;
 ~zh-Hant zht;
 ~zh-TW zht;
 ~zh-HK zht;
}

用Hexo生成网站,源文件用繁体写成。对于 hexo generate 生成得到的 nginx-accept-language-zhs-zht.html ,用 OpenCC 转换得到简体版本:nginx-accept-language-zhs-zht.html.zhs.html 。视情况还需要转换其他一些文件,比如 atom.xml 、 提供“阅读最多文章”功能 的 popular.json 。

# zsh
cd ~/maskray.me/public
opencc -c t2s.json -i atom.xml -o atom.xml.zhs.xml
for i in **/*.html 20*; do # 选择需要简繁体支持的文件
 c=${#${(s/.html/%)i}//[^%]/} # 计算子串`.html`出现次数
 if (( $c <= 1 )); then   # 出现一次的为原始文件,需要转换成简体
 opencc -c t2s.json -i $i -o $i.zhs.html
 fi
done
#在Nginx配置文件中指定需要简繁体支持的路由
location ~ ^/blog/20?? {
 try_files $uri.$lang.html $uri =404;
 add_header Vary Accept-Language;
}
location ~ /atom.xml {
 try_files $uri.$lang.xml $uri =404;
 add_header Vary Accept-Language;
}
location ~ \.json$ {
 try_files $uri.$lang.json $uri =404;
 add_header Vary Accept-Language;
}# 其他需要简繁体支持的路由
#根据http请求头中的accept-language转发到不同的页面
if ($http_accept_language ~* ^zh){
    set $lang "/index_cn.jsp";
}
if ($http_accept_language !~* ^zh){
    set $lang "/index_en.jsp";
}
 
location =/ {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_pass http://localhost:8080$lang;
}

Last updated