Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 959
Toma Tomov Avatar asked Nov 14 '25 22:11

Toma Tomov


1 Answers

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
like image 85
anubhava Avatar answered Nov 17 '25 20:11

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!