I have URL like the following structure:
xyz/asset.html
abc/test.html
xyz/abc/test.html
xyz/abc/qwerty/test2.html
I would like to redirect:
xyz/asset.html to xyz/asset
xyz/abc/test.html to xyz/abc/test
xyz/abc/qwerty/test2.html to xyz/abc/qwerty/test2
Currently I've this redirect rule in my ngnix configuration and it's working for the first level directory redirect:
location ~ ^/(xyz|abc).html { return 301 /$1; }
This works for first level of direct but not working for subdirectories. How to achieve this? Thanks for the help.
There are multiple ways to solve this. Here's one such way...
The first step is to capture the part of the URI that needs to rewritten. Then, we can do the redirection using either a
location
block or usingrewrite
condition.Using
location
block withnamed capture
...Or
Using
rewrite
...Nginx supports
named captures
using the following syntax:Ref: https://nginx.org/en/docs/http/server_names.html (under the header Regular expressions names).