11

Nginx根据Accept-Language的简繁体支持

 4 years ago
source link: http://maskray.me/blog/2015-10-06-nginx-accept-language-zhs-zht
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Nginx根据Accept-Language的简繁体支持

这个功能开启很久了,但直到昨天才发现遗漏了atom.xml……

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

在Nginx配置文件中与server块同级的地方加上:

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

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

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

在Nginx配置文件中指定需要简繁体支持的路由,

server {
# ......
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;
# ......

Share Comments


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK