Httpd – If else condition Apache 301 redirect

301-redirectapache-2.4httphttpd

I have multiple URL's that looks something like this :

  • stage-app-platform-com.something.com
  • stage.something.com
  • stage1.something1.com

I wanted to create an Apache 301 redirect rule which, if the URL contains the pattern app-platform should forward to stage1.app.com and any other request hitting the server should be redirected to stage2.app.com. To do so, I wrote the following redirect rule:

RewriteRule ^stage-app-platform-com$ https://stage1.app.com/ [L,R=301]
RewriteRule ^(.*)$ https://stage2.app.com/ [L,R=301]

Now the second rule which states all the traffic hitting should be re-directed to https://stage2.app.com/ works but the first one doesn't seem to work. If the first URL is requested Apache forwards to the https://stage2.app.com/ instead of https://stage1.app.com/

As I am pretty much new to writing re-write rules, I am finding it a bit difficult. I would appreciate any help.

Best Answer

Try the following. But first explicity clear your browser cache. Redirects are often cached.

<if "%{HTTP_HOST} =~ /^stage-app-platform-com\./">
   Redirect permanent https://stage1.app.com/
</if>
<else>
   Redirect permanent https://stage2.app.com/
</else>
Related Topic