Score:1

Location redirect from domain to another one in nginx

cn flag

I want to redirect locations play.example.com/u/<user id> to example.com/u/<user id> and play.example.com/b/<game id> to play.example2.net/b/<game id>

While having options for website too (webroot and api which i host on same domain). How can I achieve that?

Score:4
us flag

If i understood your question properly, this should work:

server {
  server_name play.example.com;

...

  location ~ ^/u/(.*)$ {
    return 301 $scheme://example.com/u/$1;
  }

  location ~ ^/b/(.*)$ {
    return 301 $scheme://play.example2.net/b/$1;
  }
}
us flag
Edited answer, please try it there is regex in location, you can validate userid and gameid by symbols, at the moment it allow any text after these locations
us flag
It is a good practice to use at least the start anchor `^` in the regular expression: `location ~ ^/u/(.*) {`. The curreent location blocks match `.*/u/`, which is too wide match.
us flag
Yes, you're absolutelly right, i corrected answer, thanks
ws flag
Never use a 301 redirect unless you are sure that's what you want to do and it has been thouroughly tested with a temporary redirect (302)
Score:0
cn flag

Just this morning was curious how to selectively redirect some but not all paths to another host.

Using the $request_uri variable saves us from writing regexes:

location /u/ { 
  return 301 $scheme://play.example2.net$request_uri;
}

Only requests matching /u/... will enter the location block and trigger the return 301. This will redirect to the corresponding /u/... location on the target host since the $request_uri includes the matched location prefix.

The trailing slash in the location is important, as otherwise it would redirect for any path starting with /u... like /user or /ultron. Tho this means it won't redirect requests to naked /u.

If you want to redirect the naked /u as well, define another location with the = prefix:

location = /u {
  return 301 $scheme://play.example2.net$request_uri;
}

The order of the two locations in the file doesn't matter. Nginx will prioritize match to = /u before the others prefixed with /u....

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.