Nginx geoip redirect , but exclude URL

霸气de小男生 提交于 2021-01-29 11:10:04

问题


Currently, I have the following setup for GeoIP redirect in Nginx:

set $fromAU 0;
set $isAUuri 0;
set $isUSuri 0;
if ( $geoip_country_code = "AU" ) { set $fromAU 1; }
if ( $request_uri ~* "^/australia" ) { set $isAUuri 1; }
if ( $request_uri ~* "^/usa-can" ) { set $isUSuri 1; }
if ( $request_uri ~* ^/(wp-admin|wp-login\.php) ) { set $isUSuri 1; }
set $redirectableAU "${fromAU}${isAUuri}";
if ( $redirectableAU = "10"  ) { rewrite "^(/australia)?(.*)" $scheme://$host/australia permanent; }
if ( $redirectableAU = "01"  ) { rewrite "^(/australia)?(.*)" $scheme://$host/usa-can permanent; }
set $redirectableUS "${fromAU}${isUSuri}";
if ( $redirectableUS = "00"  ) { rewrite "^(/australia)?(.*)" $scheme://$host/usa-can permanent; }

which works as intended with one slight issue:

domain.com/wp-admin -> works as intended

domain.com/usa-can/wp-admin -> works as intended

domain.com/australia/wp-admin -> redirects to /usa-can

I am trying to work out the GeoIP redirect for the USA and AU regions, which on the frontend works just fine, but the issue is with last wp-admin redirect, any insights will be greatly appreciated :)


回答1:


I would use the map module from nginx as it is optimized for fast lookups. https://nginx.org/en/docs/http/ngx_http_map_module.html

# partly adopted from 
# https://www.digitalocean.com/community/tutorials/how-to-use-nginx-s-map-module-on-ubuntu-16-04

# My countries
#
map $geoip_country_code $fromAU {
    default 0;
    AU 1;
}

map $request_uri $redirect_uri {
    default /wp-admin;
     ~*^/australia /australia/wp-admin;
     ~*^/usa-can /usa-can/wp-admin;
}

if ( $fromAU = "1"  ) { redirect $scheme://$host/$redirect_uri permanent; }
if ( $fromAU = "0"  ) { redirect $scheme://$host/$redirect_uri permanent; }


来源:https://stackoverflow.com/questions/57071356/nginx-geoip-redirect-but-exclude-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!