5

I am trying to write a rule to permenantly redirect a domainname to another domain name

RewriteCond %{HTTP_HOST} ^www.companyname1.com$
RewriteRule ^(.*)$ http://www.companyname2.com/$1 [R=301,L]

This only works if the user remembers to type in www, if the user does not type in www in the url, the page will load but the image links will be broken.

Does anyone know how to adjust the above rule to it works with and without www?

I am using a LAMP configuration, apache 2 on redhat.

oshirowanen
  • 15,331
  • 77
  • 181
  • 330

4 Answers4

10

You can supply several optional Rewrite-Conditions with [OR]:

RewriteCond %{HTTP_HOST} ^www.companyname1.com$ [OR]
RewriteCond %{HTTP_HOST} ^companyname1.com$
RewriteRule ^(.*)$ http://www.companyname2.com/$1 [R=301,L]

This should do the trick. The first Rewrite-Condition fires, if www is present, the second one fires, if www has been forgotten.

Demento
  • 3,741
  • 2
  • 24
  • 32
  • 3
    The symbolic name [R=permanent]" instead of the numeric 301 is slightly more optimal as it will avoid confusion in your config. from http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html use: "RewriteRule ^(.*)$ http://www.companyname2.com/$1 [R=permanent,L]" – Stickley Feb 16 '13 at 20:30
  • 1
    For me the RewriteRule http://www.companyname2.com/$1 added an extra slash after the domain, so I had to replace it with http://www.companyname2.com$1 – Florin Dumitrescu Oct 05 '13 at 11:05
  • @Stickley Wow. "slightly more optimal". You _are_ aware the "optimal" is a superlative? – arkascha Feb 13 '16 at 12:27
  • 1
    You should always take care about if it is a good idea to use `301` alias `permanent`: http://stackoverflow.com/questions/9130422/how-long-do-browsers-cache-http-301s – Martin Schneider May 16 '17 at 18:46
2

The redirect was not working for me and I had to adjust it, below is a working version based on the answer by @Demento.

# Parmenent redirect to webdesign.danols.com of all pages
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.kingston-web-design.com [OR]
RewriteCond %{HTTP_HOST} ^kingston-web-design.com
RewriteRule ^(.*)$ http://webdesign.danols.com.com$1 [R=301,L]
Daniel Sokolowski
  • 10,545
  • 3
  • 61
  • 49
1

If you don't care what the hostname starts with then don't root the regex, just check that it ends with companyname1.com.

As for the leading slash just add it at as optional to the root of your regex.

RewriteCond %{HTTP_HOST} companyname1.com$
RewriteRule ^/?(.*) http://www.companyname2.com/$1 [R=permanent,L]
Brad Giaccio
  • 145
  • 1
  • 4
0

Or just by using simple regex:

RewriteCond %{HTTP_HOST} ^(www.)?companyname1\.com$
RewriteRule ^(.*)$ http://www.companyname2.com/$1 [R=301,L]
j3141592653589793238
  • 1,490
  • 1
  • 13
  • 29