繁体   English   中英

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

[英]htaccess redirect subdomains to certain page?

我需要将所有子域都重定向到特定页面,而无需实际更改URL,因为我将根据URL中的子域在此特定页面上显示不同的内容。

假设我的网站位于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上,我有一些将捕获URL的代码,如果url为abc.testdomain.com,它将显示某些内容,而如果子域为xyz.testdomain.com,它将显示不同的内容。

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

使用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]

这意味着您无需担心找出请求来自脚本内部的位置(我不确定这实际上可能是不可能的)。 相反,您可以将其作为普通参数读取(它也像普通参数一样容易被黑客入侵;请务必对其进行清理)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM