Reputation: 617
I'm trying to do this in a nginx conf file but it doesn't work :
if ($scheme://$host = 'http://example.com') {
return 301 https://example.com$request_uri;
}
So how can I concatenate $scheme and $host in the if condition ?
Upvotes: 4
Views: 3954
Reputation: 5266
I was also searching how to use Nginx's if
with a concatenated string. I found this question, and a bunch of other articles saying "if is evil", but not offering a replacement.
And then I ran into this question, which led me to a solution that is much more compact and elegant - especially when you need multiple if
cases, so I'll post it for other searchers.
map "$scheme://$host" $myVar {
default 0;
"http://example.com" 1;
"~*(www\.)?example" 1;
# add more if needed
}
Basically, this compares the first argument from the first line (the concatenated $scheme://$host
) with first arguments from other lines (http://example.com
literal, ~*(www\.)?example
regex case insensitive, or default
by default), and assigns the second arguments from corresponding lines (1
or 0
in our case, could be anything) to the variable passed as the second argument on the first line ($myVar
).
Saving a lot of extra lines of code if you need 10+ ifs
Upvotes: 2
Reputation: 634
It's easy with a temp variable
set $tmp $scheme://$host;
if ($tmp = 'http://example.com') {
return 301 https://example.com$request_uri;
}
Upvotes: 4