.htaccess

httaccess redirect based on part of url


I am trying to redirect any url that contains api to another one. Example:

OLD: https://old-domain/api/lalala
REDIRECT: https://new-domain/api/lalala

What I must not redirect:

https://old-domain/lalala

What I am trying is

RewriteEngine On
RewriteBase /

#Tried this one
#RewriteRule ^https://old-domain/api/(.*)$ https://new-domain/api/$1 [L,R=301]

#And this one
RedirectMatch 301 costercatalog.com/api/(.*) https://new-domain/api/$1

Testing in htaccess tester but the rule doesn't match.


Solution

  • You don't match domain name in RewriteRule. What you need is just a simple redirect rule like this in the site root .htaccess file of the old domain:

    RewriteEngine On
    
    RewriteRule ^api/.* https://new-domain/$0 [L,NE,NC,R=301]
    

    Note that $0 represents full match of RewriteRule pattern.


    A note on the second attempt:

    RedirectMatch directive comes from a different Apache module, one that doesn't require RewriteEngine On. Above redirection can be handled independently by RedirectMatch as well with the following rule:

    RedirectMatch 301 ^(/api/.*) https://new-domain/$1