If/else (conditional) reverse_proxy

Hi, currently I am using the geoip plugin to check the user’s country.
And I’m trying to do if/else in Caddy file, I’ve been searching for quite some time, but I still don’t have a definite solution. I want 2 conditions

if {geoip.country_code} == "US" {
 reverse_proxy localhost:3000
}else if {geoip.country_code} == "HK"{
 reverse_proxy localhost:3001
}

I’m not sure if caddy supports such condition? If anyone comes across this thread, please help me out a bit. I’m really grateful

1 Like

Two ways come to mind:

@us vars {geoip.country_code} US
@hk vars {geoip.country_code} HK
reverse_proxy @us localhost:3000
reverse_proxy @hk localhost:3001

Or:

map {geoip.country_code} {backend} {
    US localhost:3000
    HK localhost:3001
}
reverse_proxy {backend}

See docs for:

2 Likes

thanks a lot. And if the case

how to set default for other country_code?

yesterday i tried this way, it seems to be working. But I don’t know if it’s correct or not

@othercountry expression `{geoip.country_code} != "HK"`
@HK expression `{geoip.country_code} == "HK"`
reverse_proxy @othercountry localhost:3000
reverse_proxy @HK localhost:3001

only recognize if it is HK then : 3001. All other countries default to :3000

Caddy will sort handlers with a matcher higher than those without, so you don’t need the condition for the “else” case, and reverse_proxy is a terminal handler (by default) so it will be the last thing to run in the middleware chain:

@HK expression `{geoip.country_code} == "HK"`
reverse_proxy @HK localhost:3001
reverse_proxy localhost:3000

But in general, I’d recommend using handle blocks to implement mutual exclusivity, especially if you’re not simply using a single directive of the same kind, in either case.

@HK expression `{geoip.country_code} == "HK"`
handle @HK {
	reverse_proxy localhost:3001
}

handle {
	reverse_proxy localhost:3000
}
2 Likes

it’s great, looks like i have completed and can customize more than reverse_proxy , thank you so much

This topic was automatically closed after 30 days. New replies are no longer allowed.