Score:1

Ngnix redirect for multilevel subdirectories

ma flag

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.

Score:1
sv flag

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 using rewrite condition.

Using location block with named capture...

location ~ ^/(?<variable>[/a-zA-Z0-9]+)\.html$ { return 301 /$variable; }

Or

location ~ ^/([/a-zA-Z0-9]+)\.html$ { return 301 /$1; }

Using rewrite...

rewrite ^/(?'custom_url'[/a-zA-Z0-9]+)\.html$ /$custom_url permanent;

Nginx supports named captures using the following syntax:

?<name>     Perl 5.10 compatible syntax, supported since PCRE-7.0
?'name'     Perl 5.10 compatible syntax, supported since PCRE-7.0
?P<name>    Python compatible syntax, supported since PCRE-4.0

Ref: https://nginx.org/en/docs/http/server_names.html (under the header Regular expressions names).

ma flag
Thanks for the answer Pothi. I tried the location rule you provided. It's working for 2nd level sub-dir (xyz/abc/test.html to xyz/abc/test) but not for (yz/abc/qwerty/test2.html to xyz/abc/qwerty/test2).
sv flag
If you used `location` rule, then please make sure to have a default `location` rule as well such as `location / {}`. Here's the sample repo to test the above scenario with the test URL available (temporarily for now)... https://github.com/pothi/qa-nginx/tree/main/serverfault/1070388
ma flag
Thanks mate! That was helpful. It worked.
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.