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
  • 13,315
Igor
  • 135

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
  • 13,315