Ngnix redirect for multilevel subdirectories
Solution 1:
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).