Score:0

How to set proxy_pass conditionally based on $host value?

ve flag

I am trying to set proxy_pass based on $host value, I tried this:

location /api/v1/ {
    if ($host = .*\.npreprod.company.com)
    {
            proxy_pass https://frontend-api.preprod.company.com/api/v1/;
    }
}

however, I got the error

nginx: [emerg] "proxy_pass" cannot have URI part in location given by regular expression, or inside named location, or inside "if" statement, or inside "limit_except" block in /etc/nginx/sites-enabled/nuxtjs.conf:45

so, what's the proper way to achieve this?

jp flag
Does this answer your question? [Nginx location regex doesn't work with proxy pass](https://serverfault.com/questions/649151/nginx-location-regex-doesnt-work-with-proxy-pass)
in flag
I don't think this is the correct duplicate. I'm pretty sure we already have one or more questions addressing the [if is evil problem](https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/), but I can't find one right now.
simo avatar
ve flag
@AlexD I am not sure how would I apply the answer at that question in my case
jp flag
@GeraldSchneider this one describes how to match a hostname better https://serverfault.com/questions/286828/nginx-matching-server-host-name-in-location-directive
Richard Smith avatar
jp flag
Rather than testing the value of `$host` inside the `server` block, you could create a separate `server` block. See [this document](http://nginx.org/en/docs/http/server_names.html).
simo avatar
ve flag
Thanks@AlexD , yes, that's what I ended doing, it worked well.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.