Sunday, January 29, 2017

How to redirect multiple dynamic URLS with apache

Leave a Comment

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?

1 Answers

Answers 1

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.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment