Joaquin Colella
Joaquin Colella

Reputation: 105

How to redirect non-www to www in my domain

I'm having a problem I just want to redirect the mydomain.com to www.mydomain.com, but the solutions I've found make my oder subdomains like admin.mydomain.com redirect to www.admin.mydomain.com. I have an Ubuntu 14.04 with Apache and working with Laravel (PHP).

I just want this to happen when is the mydomain.com/.... to www.mydomain.com/... but no when there is something else at the beginning like admin.mydomain.com

I leave here the solution I found but that has this little problem I just explained.

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

Upvotes: 0

Views: 633

Answers (3)

Amit Ray
Amit Ray

Reputation: 3485

# Redirect anything except admin.yourdomain.com, admin1.yourdomain.com
RewriteCond %{HTTP_HOST} !^(admin|admin1)\.yourdomain\.com$ [NC]
# Redirect to www.yourdomain.com, without changing the URI
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [L,R=302]

For multiple subdomains this will work

RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} ^yourdomain.com [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Upvotes: 1

Tchoupi
Tchoupi

Reputation: 14681

You can specify the domain you want to redirect:

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

Upvotes: 1

Matt Clark
Matt Clark

Reputation: 28579

Here is the rule that I use to force the use of www.

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

This should be placed only inside of the VirtualHost that has the top level definition of the domain

ServerName exmaple.com

Each other subdomain should have their own Virtual Host definition.

Upvotes: 1

Related Questions