handsome
handsome

Reputation: 2422

redirect to www if there's no subdomain in the url

I have

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

to redirect to www.mysite.com if www is not in the url. the problem with that is that it will also add www to subdomains for example

test.mysite.com will be changed to www.test.mysite.com

how can I tweak that rule to add www only if there's no subdomain set?

Upvotes: 1

Views: 201

Answers (1)

anubhava
anubhava

Reputation: 785531

how can I twaek that rule to add www only if there's no subdomain set?

Set condition to make it work for your main domain only:

RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$ [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]

Make sure to test this in a new browser to avoid old cache.

Regex ^[^.]+\.[^.]+$ will match any domain with a single DOT so it will skip subdomains.

Upvotes: 2

Related Questions