Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I redirect subdomains that do not exist?

I am trying to redirect using .htaccess in the following fashion. I am not all that familiar with .htaccess, so I'm not sure it can be done. Also, I don't know if how I am intending to do it follows best practices for SEO.

www.domain.com                > domain.com 301

ks.domain.com                 > kansas.domain.com 301

ia.domain.com                 > iowa.domain.com 301

domain.com/sites              > domain.com 301

domain.com/sites/iowa         > iowa.domain.com 301

nonexistent.domain.com        > domain.com 302

domain.com/sites/nonexistent  > domain.com 302

My biggest question is if I can detect a nonexistent subdomain and redirect. I would love to see how all of the above is accomplished.

like image 836
theherk Avatar asked Apr 04 '13 03:04

theherk


1 Answers

First, you need to add wildcard subdomains by creating a subdomain with an * as its name, only if your web host allows you to do so. And this must be in your .htaccess, try to test it to see if it works:

Options +FollowSymlinks
RewriteEngine on

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

RewriteCond %{HTTP_HOST} ^ks\.domain\.com
RewriteRule ^(.*)$ http://kansas.domain.com/$1 [R=301]

RewriteCond %{HTTP_HOST} ^ia\.domain\.com
RewriteRule ^(.*)$ http://iowa.domain.com/$1 [R=301]

RewriteCond %{HTTP_HOST} ^domain\.com
RewriteCond %{REQUEST_URI} ^/sites/?$
RewriteRule ^(.*) / [R=301]

RewriteCond %{HTTP_HOST} ^domain\.com
RewriteCond %{REQUEST_URI} ^/sites/iowa/?$
RewriteRule ^(.*) http://iowa.domain.com/ [R=301]

RewriteCond %{HTTP_HOST} ([a-z0-9-]+)\.domain\.com$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*) http://domain.com/ [R=302]

RewriteCond %{HTTP_HOST} ^domain\.com
RewriteCond %{REQUEST_URI} ^/sites/([a-z0-9-_]+)/?
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule ^(.*) http://domain.com/ [R=302]

Just use -f to test if a requested file exists and is a regular file, -s if it exists and has a file size greater than 0 and -d to test if it exists and is a directory.

like image 53
5ervant - techintel.github.io Avatar answered Sep 21 '22 03:09

5ervant - techintel.github.io