我有一种情况需要在nginx中为所有请求添加国家/地区代码。
例如,如果用户访问http://example.com:3333/html/about,那么我应该重定向(使用nginx中的重写)到http://example.com:3333/html/about?country_code=en
我有以下重写,但我得到'太多循环'。
rewrite ^(.*)$ http://$host:3333/$1?country_code=en last;
我该如何解决?
nginx.conf
server {
### USA specific config ###
if ($geoip_country_code = US) {
# do something here for USA visitors;
# root path /var/www/html/content/usa/;
rewrite ^(.*)$ http://$host:3333/$1?country_code=en last;
}
}
答案 0 :(得分:3)
if ($geoip_country_code = US) {
set $test "US";
}
if ($arg_country_code != 'en') {
set $test "{$test}_R";
}
if ($test = 'US_R') {
rewrite ^(.*)$ http://$host:3333/$1?country_code=en last;
}
答案 1 :(得分:0)
试试这个:
原:
rewrite ^(.*)$ http://$host:3333/$1?country_code=en
新:
rewrite ^(.*)(?!\?country_code=[a-z][a-z])$ http://$host:3333/$1?country_code=en
我假设nginx使用公共(?!...)
语法支持负前瞻断言。否定前瞻说,匹配(和重写)应该在网址末尾的?country_code=nn
不是时发生。 (如果它位于URL的中间,则仍会发生此重写。)