How do I redirect www and non but not IP

How do I redirect www and non but not IP - .htaccess files are extremely useful in many cases for users who either do not have root permissions or for users who simply aren't comfortable in making changes in their web server's configuration file. Trying to debug .htaccess not working isn't always the easiest thing to do, however, hopefully by checking the discuss below mentioned about htaccess, mod-rewrite, redirects, ip-address, .htaccess common problems as well as the troubleshooting tips, you'll have a better grasp on what you may have to modify to get your .htaccess file running smoothly.Problem :


I am trying to redirect www.domain.com or domain.com to www.domain.com/temp.html



I am using the following code:



RewriteCond %HTTP_HOST ^.*$
RewriteRule ^/?$ "http://www.domain.com/temp.html" [R=301,L]


That works however I do not want to redirect IP. So if someone types in the static IP of the domain then I do not want them to be redirected to www.domain.com/temp.html



Anyone have the code to take care of this?


Solution :

You can make that exclusion by changing your HTTP_HOST condition:



RewriteCond %HTTP_HOST !^[0-9]1,3.[0-9]1,3.[0-9]1,3.[0-9]1,3$
RewriteRule ^/?$ "http://www.domain.com/temp.html" [R=301,L]


or the other way around:



RewriteCond %HTTP_HOST ^(www.)?domain.com$ [NC]
RewriteRule ^/?$ "http://www.domain.com/temp.html" [R=301,L]


RewriteCond %HTTP_HOST ^domain.com
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=permanent,L]


don't usethe ^.*$, that matches all, plus you can end up with a redirect loop



you can use this, that will work without typing the domain name itself in file, so can be used in any project.



RewriteCond %HTTP_HOST !^www. [NC] [or]
RewriteCond %HTTP_HOST !^[0-9]1,3.[0-9]1,3.[0-9]1,3.[0-9]1,3$
RewriteRule .? http://www.%HTTP_HOST%REQUEST_URI [R=301,L]

Additionally, if you would like to do some further testing, give the htaccess tester tool a try. It allows you to specify a certain URL as well as the rules you would like to include and then shows which rules were tested, which ones met the criteria, and which ones were executed.

Comments

Popular posts from this blog

Rewrite in Mediawiki, remove index.php, .htaccess

.htaccess rewrite wildcard folder paths from host

Using .htaccess to set a cookie and 301 redirect