Score:2

nginx different routes for / and /*

us flag

I'd like to route / to a.sock and /(.*) to b.sock.

I tried

    location / {
        proxy_pass http://unix:/tmp/a.sock;
        proxy_read_timeout 30;
        proxy_connect_timeout 30;
        proxy_redirect off;
        proxy_set_header Host               $host;
        proxy_set_header X-Real-IP          $remote_addr;
        proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto  $scheme;
    }
    location ~ /(.*) {
        proxy_pass http://unix:/tmp/b.sock;
        proxy_read_timeout 30;
        proxy_connect_timeout 30;
        proxy_redirect off;
        proxy_set_header Host               $host;
        proxy_set_header X-Real-IP          $remote_addr;
        proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto  $scheme;
    }

with different ordering too.

Can this be achived with nginx, if so, how?

My take is, according to the documentation anything ending with a / assumes a wildcard after the / and the plain route without the regex takes precedence.

Essentially the backend on b.sock has a route definition of /:term or /{term} depending on which routing lib you use, but has no handler for /. You're probably thinking "so add a handler for / and call it a day". I might do that, but it's a workaround. I would like a.sock to handle /.

So again, can this be done with nginx and how?

Richard Smith avatar
jp flag
Your regular expression `/(.*)` also matches `/`.
Gerard H. Pille avatar
in flag
Have you tried replacing "location /" by "location ~ ^/$" ?
Score:4
cn flag

Use exact matching for homepage, e.g. location = / { … }. The location / { … } will apply for the rest of the pages.

The exact matching (with equals sign) has priority over prefix location (no equals sign).

Paul avatar
cn flag
IIRC, the order is `=` where `nginx` stops processing immediately, then regex, lastly a match. I think the original config in the question is always matching on regex.
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.