NGINX url rewite rules
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I have two url patterns I that need a rewrite rule for NGINX

rewrite #1

https://domain.com/details/1020/really-long-page-title-here

needs to rewrite

https://domain.com/really-long-page-title-here-1020#home

1020 is the ID

rewrite #2

https://chicago.domain.com/details/1020/really-long-page-title-here

needs to rewrite to be

http://domain.com/chicago/really-long-page-title-here-1020#home

notice the sub domain becomes the subdirectory and the 1020 ID gets put at the end, same as rule #1

awarded to weslly

Crowdsource coding tasks.

2 Solutions

Winning solution

If by rewrite, you mean a redirect, this should work:

server {
  server_name chicago.domain.com;
  return 301 $scheme://domain.com/chicago$request_uri;
}

server {
  listen 80;
  listen 443 ssl;
  server_name domain.com;
  location ~ ^(\/(chicago\/)?details\/)(\d+)\/(.+)$ {
    return 301 "$scheme://domain.com/$2$4-$3#home";
  }
}

But if you really want a rewrite (just change the way your application receives the url, without changing it on the address bar), try this:

server {
    rewrite ^(\/(chicago\/)?details\/)(\d+)\/(.+)$ $2$4-$3#home last;
}

You can also achieve this by using a regular expression on the server name:

server {
  listen 80;
  listen 443 ssl;
  server_name ~^www\.(\w+)\.domain\.com$
  if ($http_host !~ "^(www\.)?domain\.com") {
     rewrite !^chicago\.domain.com
  }
  location / {
     rewrite ^ $scheme://$1.domain.com$request_uri permanent;
  }
}
View Timeline