0

I've the following code in my .htaccess file:

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

The code above is for adding www to the domain if it does not have the www. But I have a domain like: myloadbalancername-432566808.us-west-1.elb.amazonaws.com (DNS from AWS Elastic Load Balancer) and this domain does not work with www. So, how can I add www for all domain requests, except for the specific domain?

RewriteCond %{REQUEST_URI} !myloadbalancername
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

I tried with the code above, to check if the domain name does not have the word, and then check if the domain does not have the www, but without success. I'm beginner with .htaccess so I don't know what I'm doing wrong.

MrWhite
  • 11,643
  • 4
  • 25
  • 40
Igor
  • 125
  • 7
  • 2
    Possible duplicate of [Redirect, Change URLs or Redirect HTTP to HTTPS in Apache - Everything You Ever Wanted to Know About Mod\_Rewrite Rules but Were Afraid to Ask](http://serverfault.com/questions/214512/redirect-change-urls-or-redirect-http-to-https-in-apache-everything-you-ever) – MadHatter Dec 08 '16 at 21:59
  • @MadHatter I read about your link and I've found the `implicit AND`... It looks like my code is correct, why does it not work? – Igor Dec 08 '16 at 22:10
  • The linked duplicate is a [canonical](http://meta.serverfault.com/questions/1986/what-are-the-canonical-answers-weve-discovered-over-the-years) question; that is, one that is designed to be our last word on a particular subject. That said, four others would have to agree with me to close your question, and it looks like you've got an answer that pleases you before that happened (if indeed it ever does). So all ends well! – MadHatter Dec 09 '16 at 07:21

1 Answers1

2

As with your other condition, checking for the presence of www in the host, you need to check against the HTTP_HOST server variable again, not REQUEST_URI - which only holds the URL-path.

Try the following:

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

I've also added a start of string anchor (^) so it will fail quicker, if it is going to fail (more efficient), rather than searching for "myloadbalancername" anywhere in the host string. Also, no need to include anchors if you are capturing the whole pattern (eg. ^(.*)$ is the same as (.*)).

Clear any intermediary cache(s) before testing, as any erroneous 301s will have been cached by the browser.

MrWhite
  • 11,643
  • 4
  • 25
  • 40