簡體與繁體判斷
我想根據http首部的 accept-language 決定提供簡體或繁體的檔案。在chrome中, chrome://settings/languages 可以設定偏好語言,瀏覽器會據此設定 accept-language 首部。較好的處理方式是解析該字段,取得qvalue,根據優先順序選取最恰當的語言。但僅用於支持簡繁體,我想用取巧的辦法:忽略優先級,只要 accept-language 裡出現了 zh-hant 、 zh-tw 、 zh-hk 等字樣,就返回繁體,否則返回簡體。
1 2 3 4 5 6 | 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 。
1 2 3 4 5 6 7 8 9 | # 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}
if (( $c <= 1 )); then # 出现一次的为原始文件,需要转换成简体
opencc -c t2s.json -i $i -o $i .zhs.html
fi
done
|
登入後複製
在nginx設定檔中指定需要簡繁體支援的路由:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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轉送到不同的頁面:
直接上程式碼
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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:
}
|
登入後複製
測試:
http://www.findmaven.net是一個findjar和findmaven的搜尋引擎
瀏覽器設定(英文)


#回傳

#瀏覽器設定(中文)

返回

以上是Nginx怎麼根據不同瀏覽器語言設定頁面跳轉的詳細內容。更多資訊請關注PHP中文網其他相關文章!