nginx config for sub dir to sub domain request rewrite
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I need to suppose some legacy urls which look like this

https://domain.com/brand/widget/index/126.html

126 is the variable here that changes a lot
domain.com/brand/widget/ would be what we need to detect to see if its a url we need to redirect

and we would want to redirect 301 to
https://brand.otherdomain.com/widget/index/126.html

notice brand subdir becomes subdomain. the 126 variable should persist in the url rewrite. we should also leave room in the solution for the root domain to change as indicated by "otherdomain.com"

I want to use nginx here so our app behind doesnt need to deal with this and nginx is mega fast.

awarded to kerncy
Tags
nginx

Crowdsource coding tasks.

1 Solution

Winning solution

Hi

I didn't undesrstood the "room" part, but this line should do the work, you just have to add it to your current configuration.

rewrite ^/([a-zA-Z0-9])+/(.*) http://$1.otherdomain.com/$2 permanent;

It captures the first element of the path to set it as a subdomain, and take the other parts of the request as a new url.

Do not hesitate to contact me if you have any questions.

Edit 1 : this should be better :

location ~/brand/widget/* {
    rewrite ^/([a-zA-Z0-9]+)/(.*) http://$1.otherdomain.com/$2 permanent;
}
We would only want to capture inbound requests that match this path "domain.com/brand/widget/*" anything else not that we would leave it as is this way other urls are processed by the app behind nginx.
Qdev 3 months ago
See edit 1
kerncy 3 months ago
It’s perfect! Thx
Qdev 3 months ago