Search code examples
regex.htaccessmod-rewriteurl-rewrite-module

Tricky htaccess redirect using a wildcard for subfolder


I have a client request to rewrite the following, where "anything" can be any named directory:

https://clientdomain.com/anything/final-destination

to:

 https://clientdomain.com/final-destination

I know I can identify "anything" with the following regex:

(?<=clientdomain.com\/)(.*)(?=final-destination)

...but how to incorporate that into a working rule eludes me


Solution

  • You may use this rule without any lookahead:

    RewriteEngine On
    
    RewriteRule ^[^/]+/(final-destination/?)$ /$1 [L,NC,R=301]
    

    Here [^/]+ matches 1 or more of any character that is not /.