如何使用.htaccess重定向到包含HTTP_HOST的URL?
问题
我需要将一些简短的便捷URL重定向到更长的实际URL。该站点使用一组子域来标识一组开发或者实时版本。
我希望将某些请求重定向到的URL包括HTTP_HOST,这样我就不必为每个主机创建自定义.htaccess文件。
特定于主机的示例(从.htaccess文件中摘录)
Redirect /terms http://support.dev01.example.com/articles/terms/
对于在dev01.example.com上运行的开发版本,此示例工作正常。如果我在主.htaccess文件中使用同一行作为在dev02.example.com下运行的开发版本,则最终将被重定向到错误的位置。
理想规则(不确定正确的语法)
Redirect /terms http://support.{HTTP_HOST}/articles/terms/
该规则不起作用,仅作为我要实现的目标的一个示例。然后,我可以在许多不同的主机下使用完全相同的规则,并获得正确的结果。
答案?
- 可以使用mod_alias完成此操作,还是需要更复杂的mod_rewrite?
- 如何使用mod_alias或者mod_rewrite实现?如果可能的话,我希望有一个mod_alias解决方案。
澄清说明
我不在同一台服务器上。我想要:
- http://example.com/terms/-> http://support.example.com/articles/terms/
- https://secure.example.com/terms/-> http://support.example.com/articles/terms/
- http://dev.example.com/terms/-> http://support.dev.example.com/articles/terms/
- https://secure.dev.example.com/terms/-> http://support.dev.example.com/articles/terms/
我希望能够在example.com和dev.example.com的.htaccess文件中使用相同的规则。在这种情况下,我需要能够将HTTP_HOST称为变量,而不是在将请求重定向到的URL中从字面上指定它。
我将按照建议调查HTTP_HOST参数,但希望有一个可行的示例。
解决方案
回答
根据这份备忘单(http://www.addedbytes.com/download/mod_rewrite-cheat-sheet-v2/png/),这应该可行
RewriteCond %{HTTP_HOST} ^www\.domain\.com$ [NC] RewriteRule ^(.*)$ http://www.domain2.com/
请注意,我没有办法对此进行测试,因此应将其作为指向正确方向的指针,而不是明确的答案。
回答
如果我们停留在同一台服务器上,那么无论服务器在什么位置,都可以将其放入.htaccess中:
RedirectMatch 301 ^/terms$ /articles/terms/
产生:
http://example.com/terms -> http://example.com/articles/terms
或者:
http://test.example.com/terms -> http://test.example.com/articles/terms
显然,我们需要调整REGEX匹配等以确保它可以应付我们要扔给它的东西。 301也一样,如果我们不希望浏览器缓存重定向,则可能需要302.
如果你想:
http://example.com/terms -> http://server02.example.com/articles/terms
然后,我们需要使用HTTP_HOST参数。
回答
我们不需要包括此信息。只需提供相对于根的URI。
Redirect temp /terms /articles/terms/
在mod_alias文档中对此进行了解释:
The new URL should be an absolute URL beginning with a scheme and hostname, but a URL-path beginning with a slash may also be used, in which case the scheme and hostname of the current server will be added.
回答
听起来我们真正需要的只是别名吗?
Alias /terms /www/public/articles/terms/
回答
我认为我们将要捕获HTTP_HOST值,然后在重写规则中使用它:
RewriteCond %{HTTP_HOST} (.*) RewriteRule ^/terms http://support.%1/article/terms [NC,R=302]