Ogugua Belonwu
Ogugua Belonwu

Reputation: 2141

Redirecting non "www" to "www" and rewrite all subdomains except www

I want to have all domain.com on my website to redirect to www.domain.com

and

all subdomains that are not www.domain.com such as xyz.domain.com/abc rewritten (not a redirect as it will still show xyz.domain.com/abc on the browser) to www.domain.com/page.php?id=xyz&param=abc.

Currently I have this:

RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301]
RewriteCond %{HTTP_HOST} !^(www\.)?[^.]+\.domain\.com.*$
RewriteRule (.*) http://www.domain.com/hosted_form.php?id=$1 [L]

It successfully redirects domain.com to www.domain.com but displays server not found for mno.domain.com/efg.

Upvotes: 1

Views: 653

Answers (2)

Yazid Erman
Yazid Erman

Reputation: 1186

In Addition to Saddam Abu Ghaida Solution, which fixes your problem with non-www urls, You have to To enable wildcard subdomains to avoid the "server not found" problem for any subdomain.

If you are using Apache, Modify your httpd.conf configuration file to include the Wildcard line as following:

NameVirtualHost ?.?.?.?

<VirtualHost ?.?.?.?>
    DocumentRoot /www/subdomain
    ServerName www.domain.tld
    ServerAlias *.domain.tld
</VirtualHost>

Upvotes: 0

Saddam Abu Ghaida
Saddam Abu Ghaida

Reputation: 6729

RewriteCond %{HTTP_HOST} ^([a-z.]+)?domain.com$ [NC]  
RewriteCond %{HTTP_HOST} !^www. [NC]  
RewriteRule .? http://www.%domain.com%{REQUEST_URI} [R=301,L]

Upvotes: 1

Related Questions