Home > Software engineering >  301 Redirect to new domain with some specific URLs
301 Redirect to new domain with some specific URLs

Time:11-23

I saw similar topics but couldn't find a practical answer to my problem.

I'm moving my old website to a new one, and some URLs are changing.

I would like to make a generic 301 redirection to the new domain (because most paths are the same), while individually redirecting some URLs.

Here is what I have on my old website .htaccess :

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_HOST} ^old\.com$ [OR]
  RewriteCond %{HTTP_HOST} ^www\.old\.com$
  RewriteRule (.*)$ https://new.com/$1 [R=301,L]

  Redirect 301 "/custom/url/" "https://new.com/my-custom-url"
</IfModule>

But the 301 redirects to : https://new.com/custom/url instead of https://new.com/my-custom-url

Some of my URLs also have URL parameters I would like to redirect, such as :

Redirect 301 "/brand.php?name=Example" "https://new.com/Example"
Redirect 301 "/brand.php?name=Example2" "https://new.com/Example2"

which do not seem to work as well.

Thank you very much for your help.

CodePudding user response:

But the 301 redirects to : https://new.com/custom/url instead of https://new.com/my-custom-url

It is because your specific redirect rule appears after generic one. Moreover you are mixing mod_rewrite rules with mod_alias rules and these are invoked at different times.

Have it like this:

RewriteEngine On

# redirect /brand.php?name=anything to new.com/anything
RewriteCond %{THE_REQUEST} \s/ brand\.php\?name=([^\s&] ) [NC]
RewriteRule ^ https://new.com/%1? [R=301,L,NE]

# redirect custom URL
RewriteRule ^custom/url/ https://new.com/my-custom-url [R=301,L,NE,NC]

# redirect everything else
RewriteCond %{HTTP_HOST} ^(www\.)?old\.com$ [NC]
RewriteRule ^ https://new.com%{REQUEST_URI} [R=301,L]
  • Related