Home > Software engineering >  Redirecting Many Dynamic URLs (301)
Redirecting Many Dynamic URLs (301)

Time:09-21

I have a website that is generating dynamic URLs through categories and it outputs the same information on two separate URLs (In this example it's "buildings" and "houses")

I would like to redirect all URLs that have /buildings/ in the URL to the same one with /houses/ instead.

For example:

/buildings/united-states/arizona/tucson/

to

/houses/united-states/arizona/tucson/

There are many URLs like this and I would like to use a code that does this for all.

I have tried RewriteRule ^buildings/(\d[^/] ) /houses/$1/ [R=301,L], but it didn't seem to work (it still pointed to the /buildings/ URL.

Appreciate all your comments and guidance, thank you!

CodePudding user response:

RewriteRule ^buildings/(\d[^/] ) /houses/$1/ [R=301,L]

For some reason have a \d (shorthand character class) that matches digits 0-9 only, so this won't match the example URL. Also, [^/] would seem unnecessary if it can be followed by anything anyway.

Try the following instead:

RewriteRule ^buildings/(.*) /houses/$1 [R=302,L]

This matches /buildings/<anything>. The $1 backreference holds the <anything> part.

Test first with 302 (temporary) redirect to avoid potential caching issues and only change to a 301 (permanent) redirect once you have confirmed it works as intended. You should clear you browser cache before testing.

This needs to go near the top of your .htaccess file, before any existing rewrites.

  • Related