I have an htaccess file that is shared by multiple sites. It is a multisite setup and the code before was redirecting www to non www

  RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301] 

For one site xxx.com I have to redirect non www to www.

I have tried something like this and it isn't working

<If "%{HTTP_HOST} != 'www.xxx.com'">
<If "%{HTTP_HOST} == 'xxx.com'">
  RewriteCond %{HTTP_HOST} .
   RewriteCond %{HTTP_HOST} !^www\. [NC]
   RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
    RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

It's not working. Any help will be appreciated. Many thanks!

  • 1
    Please define “not working”. Do you get an error? Incorrect redirect? No redirect at all for any domain? Do you specifically want to maintain the protocol during the redirect and not canonicalise to HTTPS (assuming you are setting protossl earlier in your config based on the request?)? – MrWhite May 2 at 23:45

Please try

# redirect xxx.com to www.xxx.com
RewriteCond %{HTTP_HOST} ^xxx\.com$ [NC]
RewriteRule ^(.*)$ http%{ENV:protossl}://www.%{HTTP_HOST}/$1 [END,R=301]

# redirect www to non-www
RewriteCond %{HTTP_HOST} !^www\.xxx\.com$ [NC]
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http%{ENV:protossl}://%1/$1 [END,R=301]

I also changed ^ to ^(.*)$ and %{REQUEST_URI} to /$1 which is not needed, but a little bit shorter.

  • It's not working saying i have redirected too many times, site goes down. – Ali Nouman May 3 at 3:34
  • Still the same issue of multiple redirects loop. All other sites work fine just this one site xxx.com goes into multiple redirects. – Ali Nouman May 3 at 4:16
  • I will try all sites from non www to www code and see that even if that works then i would be sure that all of my sites are working on www and issue isnt with www. – Ali Nouman May 3 at 4:17
  • 1
    My bad, you need another RewriteCond in the second rule to not-redirect www to non-www (back again) if the host is www.xxx.com. – Freddy May 3 at 4:39
  • Thanks very much, it worked. You are the best :). – Ali Nouman May 3 at 5:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.