Rewrite URL using Apache for redirecting root domain

Go To StackoverFlow.com

2

I have this scenario where I would like to redirect my domains using the following scenario. Can you please advice if this can be achieved using RewriteRule in Apache?

I would like to redirect any calls made using http://www.domainname.com/url to redirect to http://domainname.com/url.

I was able to achieve the above using the following rewrite rule

# BEGIN WithoutWWW
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.domainname\.com$ [NC]
RewriteRule ^(.*)$ http://domainname.com/$1 [R=301,L]
# END WithoutWWW

If anyone tries to visit just http://www.domainname.com or http://domainname.com, I would like them to redirect to http://dname.com

How can I achieve this rule using RewriteRule in Apache? I'm also using PHP, so a solution using PHP would be valid too.

2012-04-04 18:33
by Abishek


2

Here is your combined .htaccess with your existing and new code:

RewriteEngine on

# redirect domainname.com/ or www.domainname.com/ to dname.com/
RewriteCond %{HTTP_HOST} ^(www\.)?domainname\.com$ [NC]
RewriteRule ^$ http://dname.com [R=301,L]

# append www to domainname.com    
RewriteCond %{HTTP_HOST} ^www\.domainname\.com$ [NC]
RewriteRule ^ http://domainname.com%{REQUEST_URI} [R=301,L]
2012-04-04 19:11
by anubhava


1

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule ^(.*)$ http://domainname.com/$1 [R=301,L]
2012-04-04 18:47
by hohner
not sure if you understood my question. I want http://www.domainname.com/url to be redirected to http://domainname.com/url.

But if anyone visits just the root domain (http://domainname.com or http://www.domainname.com [no /url]), then it needs to redirect to http://dname.com

I wish to combine both the rules - Abishek 2012-04-04 18:55



0

That example looks like mod_rewrite. With mod_rewrite you could do:

# BEGIN WithoutWWW
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?domainname\.com$ [NC]
RewriteRule ^(.*)$ http://dname.com/$1 [R=301,L]
# END WithoutWWW

You may want to look at http://www.workingwith.me.uk/articles/scripting/mod_rewrite

Based on your comment you want to redirect the root differently so we could do:

RewriteEngine on
#www.domainname.com & domainname.com -> dname.com
RewriteCond %{HTTP_HOST} ^(www\.)?domainname\.com$ [NC]
RewriteRule ^$ http://dname.com/ [R=301,L]

#www.domainname.com/[url] -> domainname.com/[url]
RewriteCond %{HTTP_HOST} ^www\.domainname\.com$ [NC]
RewriteRule ^(.*)$ http://domainname.com/$1 [R=301,L]
2012-04-04 18:44
by Holden
not sure if you understood my question. I want http://www.domainname.com/url to be redirected to http://domainname.com/url.

But if anyone visits just the root domain (http://domainname.com or http://www.domainname.com [no /url]), then it needs to redirect to http://dname.com

I wish to combine both the rules - Abishek 2012-04-04 18:55

Ads