htaccess将子域名重定向到某个页面?

问题描述:

我需要将所有子域重定向到特定页面,而不实际更改URL,因为我将在此特定页面上显示不同的内容,具体取决于URL中的子域。htaccess将子域名重定向到某个页面?

比方说,我的网站位于testdomain.com/site1/

我希望所有的子域,像xyz.testdomain.com/site1/甚至xyz.testdomain.com在被重定向到一个特定的页面http://testdomain.com/site1/index.php/test.php

浏览器需要加载http://testdomain.com/site1/index.php/test.php,但URL仍然是xyz.testdomain.com。

这样做的目的是让有人可以去abc.testdomain.com或xyz.testdomain.com,两者都会将用户带到testdomain.com/site1/index.php/test.php,然后test.php,我有一些代码会抓取网址,如果网址是abc.testdomain.com,它会显示特定的内容,而如果子网域是xyz.testdomain.com,它会显示不同的内容。

这是我可以在htaccess中做的事吗?如果是这样,怎么样?

+0

这是重复的。我只知道它。 – 2013-03-20 22:53:16

+0

@ColeJohnson这里有:http://*.com/questions/5790131/htaccess-subdomain-script-redirect – Dave 2013-03-20 22:55:10

使用mod_rewrite你可以一起破解它。

# Step 1: If the user went to example.com or www.example.com 
# then we don't want to redirect them. (S=1 says skip the next rule) 
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com 
RewriteRule^- [S=1] 

# Step 2: Anything else is redirected to our catcher script. 

# Option 1: keeps the path they went to, but discards the domain 
# i.e. xyz.example.com/abc/def.txt => /var/www/cgi-bin/abc/def.txt 
RewriteRule ^/?(.*) /var/www/cgi-bin/$1 [QSA,L] 

# Or Option 2: take all requests to the same file 
# i.e. xyz.example.com/abc/def.txt => /var/www/cgi-bin/myfile.php 
RewriteRule^/var/www/cgi-bin/myfile.php [QSA,L] 

QSA告诉它转发查询字符串,L告诉它停止寻找更多的重定向(不是绝对必要,但如果你有很多这种事情发生的情况的有时帮助)。

您也可以将变量作为查询参数传递给脚本,QSA标志确保它们不会替换原始值;

# xyz.example.com/abc/def.txt => /var/www/cgi-bin/myfile.php?host=xyz.example.com&path=/abc/def.txt 
RewriteRule ^/?(.*) /var/www/cgi-bin/myfile.php?host=%{HTTP_HOST}&path=/$1 [QSA,L] 

这意味着你不必担心搞清楚请求从你的脚本里面走了(这可能实际上是不可能的,我不知道)。相反,你可以把它看作一个普通的参数(它也像一个普通的参数一样可以破解;一定要对它进行消毒)。