Htaccess exclude subdomains except WWW

Hello,

I have the following .htaccess modrewrite which will forward all non-www subdomain requests to www subdomain on my multisite:

<IfModule mod_rewrite.c>
    RewriteEngine On
    #RewriteBase /

    RewriteCond %{REQUEST_URI} ^system
    RewriteRule .? index.php?/%{REQUEST_URI} [L]
    
    RewriteCond %{REQUEST_URI} ^application
    RewriteRule .? index.php?/%{REQUEST_URI} [L]

    RewriteCond %{REQUEST_URI} ^/$
    RewriteCond %{HTTP_HOST} !^www
    RewriteRule .? http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{HTTP_HOST} !^www [NC]
    RewriteRule .? http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
		
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule .? index.php?/%{REQUEST_URI} [L]
</IfModule>

I only want to forward http://domain.com/$1 requests to http://www.domain.com/$1 instead of all subdomains.

How is it possible and what is the easiest way to accomplish that?

Many thanks in advance!

One of the blocks you have there almost does what you want


RewriteCond %{REQUEST_URI} ^/$
RewriteCond %{HTTP_HOST} !^www
RewriteRule .? http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

You just need to ditch the first line so it works always, and not just in the root of your website.

When you’ve done that, you can remove the block


RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} !^www [NC]
RewriteRule .? http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

as it serves no purpose whatsoever.

Also, you can merge


RewriteCond %{REQUEST_URI} ^system
RewriteRule .? index.php?/%{REQUEST_URI} [L]

and

    
RewriteCond %{REQUEST_URI} ^application
RewriteRule .? index.php?/%{REQUEST_URI} [L]

in to


RewriteCond %{REQUEST_URI} ^(application|system)
RewriteRule .? index.php?/%{REQUEST_URI} [L]

Lastly, you should get rid of the <IfModule …> </IfModule>. Once you’ve established mod_rewrite works there is no need to ask Apache over and over again for each request.

So, you’d end up with


RewriteEngine On

RewriteCond %{HTTP_HOST} !^www
RewriteRule .? http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{REQUEST_URI} ^(application|system)
RewriteRule .? index.php?/%{REQUEST_URI} [L]
  
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .? index.php?/%{REQUEST_URI} [L]