Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I match www AND non-www in a rewritecond?

I have a rewritemap that has a list of domains to redirect. Currently I have to list www.foo.com and foo.com in the rewrite map. I was wondering if there was a way to have the rewritecond check for both www and non-www in the same line.

# Rewrite Map
foo.com file.php
www.foo.com file.php

# modrewrite
RewriteCond ${domainmappings:%{HTTP_HOST}} ^(.+)$ [NC]
RewriteCond %1 !^NOTFOUND$
RewriteRule ^.*$ www.domain.com/%1 [L,R=301]

I tried doing things like (www.)%{HTTP_HOST} or ^(www.)%{HTTP_HOST} but no luck.

like image 963
Scott Foster Avatar asked Dec 30 '10 22:12

Scott Foster


2 Answers

This should do it:

RewriteCond %{HTTP_HOST} ^(www\.)?(.+)
RewriteCond ${domainmappings:%2} ^(.+)$ [NC]
RewriteRule ^ /%1 [L,R=301]

The first RewriteCond will remove the optional www. prefix. The remainder is then used as parameter for the rewrite map in the second RewriteCond.

A plain text file rewrite map returns an empty string if no match is found:

If the key is found, the map-function construct is substituted by SubstValue. If the key is not found then it is substituted by DefaultValue or by the empty string if no DefaultValue was specified.

So if the second condition is fulfilled (note the ^(.+)$), a match has been found and %1 will contain the SubstValue (in this case file.php).

like image 127
Gumbo Avatar answered Nov 08 '22 10:11

Gumbo


From a post here

http://www.eukhost.com/forums/f15/simple-rewriterule-set-redirect-domain-6570/

RewriteEngine on
RewriteCond %{HTTP_HOST} ^xyz.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.xyz.com$
RewriteRule ^(.*)$ http://www.xyz.com/test//$1 [R=301,L]
like image 34
Nikki9696 Avatar answered Nov 08 '22 09:11

Nikki9696