apache中的虚拟主机重写规则-无需重定向就摆脱子域

问题描述 投票:1回答:1

我知道有人问过类似的问题,但对于我的一生,我似乎无法使其正常工作。

想法是将子域重写为url的一部分。我们还希望服务器处理请求而不进行远程调用,并且不要重写客户端中的url。

简单地说:http://test.example.com/(something)应解释为http://example.com/test/(something)

'something'是可选的。

我已经尝试过各种不同的解决方案,但似乎从来没有做过正确的-这是我的初次体验。

#   RewriteEngine on 
#   RewriteCond %{HTTP_HOST} ^test.example.com [NC]
#   RewriteRule ^((?!test/).*)$ /test/$1 [L,NC]

#   RewriteCond %{HTTP_HOST} ^test\.example\.com$ [NC] 
#   RewriteRule ^(.*)$  "test%{REQUEST_URI}" 
#   RewriteRule ^(.*)$ test/$1 [L]  

#RewriteEngine on 
#RewriteCond %{HTTP_HOST} ^test.example.com [NC]
#RewriteRule ^(.*)$ example.com/test/%{REQUEST_URI} [P,L,NC]

重要的是要知道example.com/test/something已经存在于其他服务器上,因此不应使用或调用。

我的想法是将test.example.com重定向到新服务器,然后通过使用另一个虚拟主机将其在新服务器上解释为example.com/test(整个应用程序正在开发,没有子域,但是我们将使用子域,直到我们设法迁移所有内容并恢复“正常”方式。

及时,我们将拥有sub1.example.com,sub2.example.com等。别名在这里可能会起到一定的作用,但我的能力不足。

感谢您的帮助!

apache .htaccess mod-rewrite vhosts
1个回答
0
投票

听起来好像您需要“反向代理”,因为example.com实际上是托管在其他服务器上。 (但是,您在注释中指出“将来” example.com将返回到同一服务器上-那时,如果子域和主域指向同一文件系统,则可能不需要“反向代理”。重写就足够了。)

要配置反向代理,您需要确保启用mod_proxy和mod_proxy_http(用于HTTPS),并根据需要启用其他一些(可选)代理模块。

对于您所需要的,您要将相同的URL路径从源传递到目标,可以在virtualhost容器中为ProxyPass子域使用ProxyPassReversetest.example.com伪指令:

ProxyPass / http://example.com/test/
ProxyPassReverse / http://example.com/test/

或者,如果您需要更复杂的映射,或者您想要/需要在.htaccess中执行此操作,则可以将mod_rewrite与P标志一起使用(如上所述):

RewriteEngine On

RewriteCond %{HTTP_HOST} ^test\.example\.com [NC]
RewriteRule ^ http://example.com/test%{REQUEST_URI} [P]

重要的是,您需要RewriteRule substitution中的绝对URL(方案+主机名)(示例中缺少)。

如果此主机仅接受对test.example.com的请求,则不需要上述条件。

请注意,REQUEST_URI服务器包含斜杠前缀,因此应在substitution字符串中将其省略。而且,由于您使用的是REQUEST_URI服务器变量,而不是使用反向引用,因此不需要RewriteRule pattern中的捕获组。即。 ^(.*)$可以简化为^。与L一起使用时,不需要P,因为它暗示L

© www.soinside.com 2019 - 2024. All rights reserved.