概述: 最近遇到一个nginx语言跳转的需求,需求一、用户打开网站首页默认将根据浏览器语言进行跳转; 需求二、如果用户在页面上选择了指定语言,那么将种下语言cookie,下次用户打开,默认将优先cookie种的指定语言。 需求三、如果项目中没有用户浏览器的对应语言,默认将选择英语版本。
注意:以下假设种的cookie名是lang . 下面为部分主要内容。
if ($http_accept_language ~* ^en){
set $lang "/en";
}
if ($http_accept_language ~* ^ja){
set $lang "/ja;
}
if ($http_accept_language ~* ^cn){
set $lang "/cn";
}
if ($http_accept_language !~* ^(en|ja|zh)){
set $lang "/en";
}
location =/ {
location =/ {
if ( $cookie_lang = "en" ){
set $cklang "/en";
}
if ( $cookie_lang = "ja" ){
set $cklang "/ja";
}
if ( $cookie_lang = "cn" ){
set $cklang "/cn";
}
if ( $cklang = '' ) {
rewrite ^/(.*)$ https://$host$lang$1 permanent;
}
if ( $cklang != '' ) {
rewrite ^/(.*)$ https://$host$cklang$1 permanent;
}
}
}
location /en {
if ( $request_method = HEAD ) {
access_log off;
}
try_files $uri /en/index.html;
add_header Cache-Control "no-cache, no-store";
add_header X-Frame-Options SAMEORIGIN;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
}
location /ja {
if ( $request_method = HEAD ) {
access_log off;
}
try_files $uri /ja/index.html;
add_header Cache-Control "no-cache, no-store";
add_header X-Frame-Options SAMEORIGIN;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
}
location /cn {
if ( $request_method = HEAD ) {
access_log off;
}
try_files $uri /cn/index.html;
add_header Cache-Control "no-cache, no-store";
add_header X-Frame-Options SAMEORIGIN;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
}

