Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem detecting empty REQUEST_URI with Apache mod_rewrite

I am running Apache witha redirect rule like this:

RewriteCond %{HTTP_HOST} ^1st-domain\.com
RewriteRule ^(.*)$ http://2nd-domain.com$1 [R=permanent,L]

This successfully redirects http://1st-domain.com to http://2nd-domain.com However, when the REQUEST_URI is empty, I want to redirect to a third domain.

RewriteCond %{HTTP_HOST} ^1st-domain\.com$
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^(.*)$ http://3rd-domain.com$1 [R=permanent,L]

But this does not work and instead redirects to 2nd-domain.com

My rules are ordered like this:

RewriteCond %{HTTP_HOST} ^1st-domain\.com$
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^(.*)$ http://3rd-domain.com$1 [R=permanent,L]

RewriteCond %{HTTP_HOST} ^1st-domain\.com
RewriteRule ^(.*)$ http://2nd-domain.com$1 [R=permanent,L]

Any suggestions? Thank you in advance.

UPDATE

  1. Empty REQUEST_URI: http:/1st-domain.com
  2. Non-empty REQUEST_URI: http://1st-domain.com/something

The first rule should direct an empty request_uri to 3rd-domain.com, the second rule should direct the non-empty request_uri to 2nd-domain.com

USEFUL TIDBIT You can turn on mod_rewrite debug with this snippet:

<IfModule mod_rewrite.c>
RewriteLog "/home/domain.com/logs/rewrite.log"
RewriteLogLevel 3
</IfModule>

Very useful debug option I hadn't known.

like image 267
pchap10k Avatar asked Apr 16 '11 06:04

pchap10k


1 Answers

This should work:

RewriteCond %{HTTP_HOST} ^1st-domain\.com
RewriteRule ^$ http://3rd-domain.com [R=permanent,L]

RewriteCond %{HTTP_HOST} ^1st-domain\.com
RewriteRule ^(.+)$ http://2nd-domain.com/$1 [R=permanent,L]

Hope it helps!

Note: REQUEST_URI is slightly different between httpd.conf and .htaccess, it starts with an extra backslash in httpd.conf. This means that in httpd.conf the first rewrite rule should be ^\/$, not just ^$.

like image 104
szemian Avatar answered Sep 19 '22 12:09

szemian