Raymond the Developer
Raymond the Developer

Reputation: 1676

How to redirect multiple dynamic URLS with apache

I am trying to redirect multiple paths some with dynamic path names that can be anything.

For example:

This is the code I have now.

RewriteEngine on

RedirectMatch "^/" "http://www.bbb.ai/nl/"
RedirectMatch "^/en/" "http://www.bbb.ai/en/"

RedirectMatch "^/media/" "http://www.bbb.ai/nl/media/"
RedirectMatch "^/media/(.*)" "http://www.bbb.ai/nl/media/"
RedirectMatch "^/en/media/" "http://www.bbb.ai/en/media/"
RedirectMatch "^/en/media/(.*)" "http://www.bbb.ai/en/media/"

RedirectMatch "^/portfolio/" "http://www.bbb.ai/nl/media/"
RedirectMatch "^/portfolio/(.*)" "http://www.bbb.ai/nl/media/"
RedirectMatch "^/en/portfolio/" "http://www.bbb.ai/en/media/"
RedirectMatch "^/en/portfolio/(.*)" "http://www.bbb.ai/en/media/"

RedirectMatch "^/team/(.*)" "http://www.bbb.ai/nl/about-us"
RedirectMatch "^/en/team/(.*)" "http://www.bbb.ai/en/about-us"

How do I achieve this?

Upvotes: 3

Views: 2414

Answers (1)

arco444
arco444

Reputation: 22821

The code in your question suggests you may be confusing two techniques of URL rewriting. RewriteEngine On provides RewriteRule functionality by mod_rewrite, but RedirectMatch is part of mod_alias.

Using either correctly should yield the correct solution for your scenario, but I will make use of RewriteRule here, so ensure that mod_rewrite is enabled on your server. I have also made an assumption that these rules are in your VirtualHost and not an .htaccess file.

RewriteEngine on

# /
RewriteRule "^/$" "http://www.bbb.ai/nl/" [R,L]
RewriteRule "^/team/?$" "http://www.bbb.ai/nl/about-us" [R,L]
RewriteRule "^/media/.+" "http://www.bbb.ai/nl/media/" [R,L]
RewriteRule "^/portfolio/.+" "http://www.bbb.ai/nl/media/" [R,L]

# /en
RewriteRule "^/en/?$" "http://www.bbb.ai/en/" [R,L]
RewriteRule "^/en/team/?$" "http://www.bbb.ai/en/about-us" [R,L]
RewriteRule "^/en/media/.+" "http://www.bbb.ai/en/media/" [R,L]
RewriteRule "^/en/portfolio/.+" "http://www.bbb.ai/en/media/" [R,L]

At the root URLs, the end anchor $ is used to make sure that they will redirect only when nothing else is present. For media and portfolio, you state in the question that they should redirect only when followed by something dynamic.

If you actually want to redirect both /portfolio and /portfolio/something-dynamic, you can do so like:

RewriteRule "^/en/portfolio(/.*)?" "http://www.bbb.ai/en/portfolio/" [R,L]

And given media and portfolio both have the same destination, you could actually combine as below:

RewriteRule "^/en/(media|portfolio)/.+" "http://www.bbb.ai/en/media/" [R,L]

Though this is less code, it is also less readable, so bear that in mind when activating the rules.

Upvotes: 6

Related Questions