Forum Moderators: phranque

Message Too Old, No Replies

301 redirect if accessing website via IP address

         

Karma

10:14 am on Oct 20, 2010 (gmt 0)

10+ Year Member



I've recently noticed that in Google webmaster tools under "Your site on the web >> Links to your site", the number one site linking to my website is my own website's IP address!

Is there anything I can add to my .htaccess to redirect any incoming connections with an IP address to [mydomain.com...] ?

I already have the following:


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

jdMorgan

12:38 pm on Oct 20, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Simply redirect any request for any hostname that is not blank and not *exactly* correct:

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

You may wish to add an exclusion for your own (single) IP address, to allow you to access the site in the case of a DNS failure. That can be done with one additional RewriteCond:

RewriteCond %{REMOTE_ADDR} !=123.45.67.89

or for a 256-address block, for example:

RewriteCond %{REMOTE_ADDR} !^123\.45\.67\.

More-complex solutions are needed if you support (or intend to support) other domains or subdomain on this server.

Jim

Karma

1:35 pm on Oct 20, 2010 (gmt 0)

10+ Year Member



Many thanks - that actually caused a redirect loop, so I removed the www\. from the 1st line, I now have:

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

Many thanks again jdMorgan, really is appreciated.

jdMorgan

3:37 pm on Oct 20, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Yes, sorry -- I post that code so often with "www" that I forgot to modify the RewriteCond pattern... :(

Glad you got it sorted.

Jim