【问题标题】:nginx conf file: Detect if browser language is "de", then redirect to page .... else redirect to other pagenginx conf文件:检测浏览器语言是否为“de”,然后重定向到页面....否则重定向到其他页面
【发布时间】:2020-01-29 11:38:11
【问题描述】:
我想在横幅中创建一个链接以重定向到两个页面之一。链接指向subdomain.example.com/email。如果浏览器语言是“de”,则转到www.example.de/banner,否则转到www.example.com/banner。我的 nginx conf 语言技能不好,但我知道德语的任何浏览器语言的前两个字符都是“de”(参见https://www.metamodpro.com/browser-language-codes)。没有其他语言有这个。
location /email {
if $http_accept_language === "de" { return 301 https://www.example.de/banner }
else { return 301 https://www.example.com/banner}
}
【问题讨论】:
标签:
nginx
http-redirect
nginx-config
【解决方案1】:
区域设置由浏览器确定的类似用例。仅提供两种语言,因此我为此使用http_accept_language。已定义标准语言,在本例中为英语。
map $http_accept_language $lang {
default en;
~de de;
}
server {
...
rewrite ^/$ /$lang/ redirect;
...
}
重新加载配置后,可以使用 curl 检查行为。
curl -I https://www.your-site.com/ -H "Accept-Language: fr"
curl -I https://www.your-site.com/ -H "Accept-Language: de-CH"
curl -I https://www.your-site.com/ -H "Accept-Language: en-US"
现在测试服务器响应,标头参数location 现在根据Accept-Language 显示正确的后缀。
location: https://www.your-site.com/en/
简短说明,Accept-Language 允许使用 q-list 进行列表,例如de, en-US;q=0.9, es;q=0.1。上面的配置不支持这个。就我而言,这根本没有必要。
https://www.w3.org/International/questions/qa-accept-lang-locales.en
【解决方案2】:
更简洁且可扩展的解决方案使用map 指令。
例如:
map $http_accept_language $redirect {
default https://www.example.com/banner;
~de https://www.example.de/banner;
}
server {
...
location /email {
return 301 $redirect;
}
...
}
详情请见this document。