How do I redirect subdomains that do not exist?

只谈情不闲聊 提交于 2019-11-30 21:48:31
5ervant

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.

If you want specific subdomains that do not exist, well you'll just have to create them, and then redirect.

To catch all erroneous subdomains, say I accidentally type metaa.stackoverlow.com, use a wildcard: *.stackoverflow.com. In cpanel, this just involves ticking a checkbox that asks 'make wildcard?' or similar. To edit .htaccess directly, just enter * in place of each specific subdomain.

Note that this also applies for any directories:

subdomain.site.com/*

*.site.com/dir

*.site.com/*

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!