2016-10-25 30 views
0

有没有一种更简单的方式来获取正则表达式中的域名,并在重写中转发而不是下面的例子?更简单的做法或在apache2重写?

现在我抓住“每一个”域,并对www.domain [A | B | C] .com进行重写。 而且我还需要在每个域中都抓住“*。域名[A | B | C] .com”和“域名[A | B | C] .com”。

<VirtualHost *:80> 
     RewriteEngine On 

     #domainA.com 
     RewriteCond %{http_host} ^domainA\.com$ [OR,NC] 
     RewriteCond %{http_host} ^(.+)\.domainA\.com$ [NC] 
     RewriteRule ^\/?(.*)$ http://www.domainA.com/$1 [R=301,L] 

     #domainB.com 
     RewriteCond %{http_host} ^domainB\.com$ [OR,NC] 
     RewriteCond %{http_host} ^(.+)\.domainB\.com$ [NC] 
     RewriteRule ^\/?(.*)$ http://www.domainB.com/$1 [R=301,L] 

     #domainC.com 
     RewriteCond %{http_host} ^domainC\.com$ [OR,NC] 
     RewriteCond %{http_host} ^(.+)\.domainC\.com$ [NC] 
     RewriteRule ^\/?(.*)$ http://www.domainC.com/$1 [R=301,L] 

</VirtualHost> 

<VirtualHost *:80> 
     Servername servername.com 

     ServerAlias www.domainA.com www.domainB.com www.domainC.com 

     # Server config stuffz here 

</VirtualHost> 

如果这是模糊的,我会尽力解释更多:)

-
问候福尔克

回答

0

你可以重写3个规则之一:

RewriteCond %{HTTP_HOST} (?:.+\.)?(domain[ABC]\.com)$ [NC] 
    RewriteRule .* http://www.%1$0 [R=permanent,L] 
  • domainA.com或* .domainA.com可写为(?:.+\.)?domainA\.com
    • (.+\.)?使子域部分可选
    • 最终的子域部分不重复使用,所以我们可以使用非捕获子模式((?: ...)
  • DOMAINA或域B或domainC = domain[ABC](如果真实的,它是foo,bar和doe,使用(?:foo|bar|doe)代替)
  • 我们可以将最后一个RewriteCond的捕获重新捕获到Rewritule。与RewriteRule(第一个参数)捕获的区别在于它们的前缀是%而不是$。所以%1将对应于domainA.com或domainB.com或domainC.com
  • 我也改写^\/?(.*)$ + $1.* + $0
    • 没有必要逃避/,这不是一个元字符,并用阿帕奇regexpes没有任何分隔符(不喜欢从PHP参看preg_ *)
    • $0是一个特殊的捕捉这需要整个模式相匹配的子字符串(路径 - 它或部分目录上下文中)

编辑:是的,我的不好,我忘了你不在目录上下文中:在%1$0之间不需要斜杠,$0捕获的子字符串已经包含URL路径的前导斜杠。

+0

这只是美丽的,我搜索的例子是(?:foo | bar | doe)。 目前,我只是得到了www.//,但我会如果我能看到最新的错误,并更新评论/问题/答案。 – Falk

+0

我已经做了一些测试在 - > [链接](http:但是我无法得到预期的结果,使用RewriteCond%{HTTP_HOST}(?:。+ \。)(?:foo \ .com | bar \ .com | doe。\ com) $ [NC] RewriteRule。* http://www.%1/$0 [R = permanent,L] – Falk

+0

Humm,无法编辑注释.. RewriteCond%{HTTP_HOST}(?:。+ \。)(?: foo \ .com | bar \ .com | doe。\ com)$ [NC] RewriteRule。* http://www.%1/$0 [R = permanent,L] – Falk

0

为@julp解决方案回答了我的情况下结束这样的:

<VirtualHost *:80> 
     RewriteEngine On 

     RewriteCond %{HTTP_HOST} (?:.+\.)?(foo\.com|bar\.com|doe\.com)$ [NC] 
     RewriteRule .* http://www.%1$0 [R=permanent,L] 

</VirtualHost> 

<VirtualHost *:80> 
     Servername servername.com 

     ServerAlias www.foo.com www.bar.com www.foobar.com 
     # Server config stuffz here 

</VirtualHost> 

我不得不这样做唯一不同的是:

RewriteRule .* http://www.%1/$0 [R=permanent,L] 

改变,没有结尾的斜线:

RewriteRule .* http://www.%1$0 [R=permanent,L] 

这里有一些讨论:https://serverfault.com/questions/24130/why-do-i-get-a-double-trailing-slash-depending-on-where-my-rewriterule-is-locate