rhorne
rhorne

Reputation: 161

Setting up a .htaccess file subdomains but also non www. to www

We have an Opencart web shop setup that uses various sub domains. I'm trying to configure our .htaccess file to do the following but can't quite get over the finish line.

Our site is setup this way:

Main Domain:

ourdomain.com

Sub Domains x 10

sub1.ourdomain.com

sub2.ourdomain.com

sub3.outdomain.com

Here's what must happen:

All visitors to the http version of the main domain or the subdomains must be redirected to https.

Visitors to any of the sub domains must be redirected to https://subdomain.ourdomain.com but without the www.

Visitors to https://ourdomain.com must be redirected to https://www.ourdomain.com.

Basically I always need visitors to the main domain to be directed to the www. version to ensure that the CSS files render correctly. Icons and graphics are missing if www. is missing.

I've currently got it configured to redirect all visitors to https but I don't know how to apply www. to only the main domain.

Hope that all makes sense.

My current code:

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

Upvotes: 1

Views: 245

Answers (1)

Amit Verma
Amit Verma

Reputation: 41219

You can use these rules :

RewriteEngine on

#Redirect "http://sub.example.com" to "https://sub.example.com"#
RewriteCond %{HTTP_HOST} ^((?!www\.).+)\.example\.com$ [NC]
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R]
#Redirect "http://example.com" or "http://www.example.com"  to "https://www.example.com"#
RewriteCond %{HTTP_HOST} ^example\.com$ [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R]

Replace example.com with yourdomain.com in the RewriteConds above.

Upvotes: 1

Related Questions