.htaccess 将所有子域重定向到不同域的子域

.htaccess 将所有子域重定向到不同域的子域,.htaccess,mod-rewrite,redirect,dns,subdomain,.htaccess,Mod Rewrite,Redirect,Dns,Subdomain,嗨,我需要重定向一个域中的所有子域到同一子域,但在不同的域。我猜最好的方法是通过一个htaccess文件,但我不确定该文件会是什么样子 Example: sd1.example.net ---> sd1.example.com sd2.example.net ---> sd2.example.com sd3.example.net ---> sd3.example.com 但是我需要对example.net中的所有子域都这样做。谢谢。如果您的Apache服务器运行

嗨,我需要重定向一个域中的所有子域到同一子域,但在不同的域。我猜最好的方法是通过一个htaccess文件,但我不确定该文件会是什么样子

Example:
sd1.example.net  --->  sd1.example.com
sd2.example.net  --->  sd2.example.com
sd3.example.net  --->  sd3.example.com

但是我需要对example.net中的所有子域都这样做。谢谢。

如果您的Apache服务器运行在
example.net
上,并且所有子域的请求都在同一父目录中,您可以执行以下操作:

RewriteEngine On

### Find the subdomain part (it will be available in %1)
### Use one of the RewriteCond-s and delete the other one

# Only redirect subdomains, not plain example.net
RewriteCond %{HTTP_HOST} ^(.*)\.example\.net$

## Redirect both subdomains and plain example.net (uncomment to enable)
#RewriteCond %{HTTP_HOST} ^(.*\.)?example\.net$

# Find the path requested (it will be available in $0)
# This rule does not attempt to match the domain, only the path
# Redirect subdomain and path to example.com
RewriteRule ^.*$ http://%1.example.com/$0 [L]
我尚未对此进行测试,因此它可能缺少查询字符串等。它还将不必要地重定向到
https://
http://
。只要你有一个可以影响你所有子域的.htaccess文件,这应该是可行的,或者至少是一个很好的起点。查看以了解有关其工作原理的更多信息

编辑 最近,我自己也希望能够做到这一点,因此我设计了一个简短的.htaccess文件,它可以实现以下功能:

RewriteEngine on

RewriteCond %{HTTP_HOST} ^(.*\.)?olddomain\.com$
RewriteRule ^(.*?/)?public_html/(.*)?$ "http\:\/\/%1newdomain\.org\/$2" [R=301,NE,L]
它采用以下文件结构:

.htaccess
public_html/
+-content
lots/
+-public_html/
| +-content
of/
+-public_html/
| +-content
subdomains/
+-public_html/
  +-content
我的主要网站(
newdomain.org
)位于
/public\u html/
中。我有许多子域,例如
subdomains.newdomain.org
,它位于
/subdomains/public\u html/
中。这使我的每个子域的所有文件彼此和我的主站点完全分开。(我的托管服务推荐
/public\u html/
/public\u html/subdomains/
,但这意味着每个子域也可以通过
newdomain.org/subdomains/
访问,这不是我想要的)。这给我的唯一限制是,我永远不能拥有一个名为
public\uhtml
的子域,我想你会同意这是完全可以接受的

规则上的标志如下所示:

  • R=301
    -重定向时永久移动
    301
    code。如果不需要永久重定向,可以更改代码,例如
    302
  • NE
    -无编码-不URI编码新地址,即将
    %
    保留为
    %
    ,而不是
    %25
  • L
    -上次-停止处理规则
请注意
.htaccess
文件必须位于web服务器的根目录中,而不是包含内容文件的目录中。这是因为重写规则在文件系统级别工作,而不是URL地址级别

地址:

  • any.subdomain.olddomain.com/any/address.html?any=query&you=like
更改为:

  • any.subdomain.newdomain.org/any/address.html?any=query&you=like