2013-11-15 28 views
1

我想编写一个rewriterule来搜索子目录中的robots.txt和sitemap.xml文件,该子文件夹中的域名与或不与www匹配。让我们举个例子:RewriteCond in .htaccess搜索域子文件夹中的robots.txt和sitemap.xml

  • 我有域aaa.com,bbb.com和ccc.com
  • 它们都安装在相同的根文件夹%{DOCUMENT_ROOT}
  • 它们可以与被访问或没有www。

如果有人试图访问http://aaa.com/robots.txt文件,我想执行以下操作:

如果请求的文件是robots.txt的{

  • 如果有一个匹配的文件子文件夹%{DOCUMENT_ROOT} /aaa.com/robots.txt(给此文件并停止)* 1
  • 否则如果存在与子文件夹匹配的文件 %{DOCUMENT_ROOT} /www.aaa.com/robots.txt (给这个文件并停止)* 2
  • 否则给文件%{DOCUMENT_ROOT} /robots.txt的* 3

}

我不想硬编码的域名;我试图把他们从请求,但我无法检查条件* 2和* 3:

RewriteCond %{REQUEST_URI} ^/robots.txt$ 
RewriteRule ^robots\.txt$ /www\.%{HTTP_HOST}/robots\.txt [L] 
RewriteCond %{REQUEST_URI} ^/sitemap.xml$ 
RewriteRule ^sitemap\.xml$ /www\.%{HTTP_HOST}/sitemap\.xml [L] 

谢谢你的帮助!

回答

0

尝试:

# prevent any kind of looping: 
RewriteCond %{ENV:REDIRECT_STATUS} 200 
RewriteRule^- [L] 

# first check host/robots.txt 
RewriteCond %{HTTP_HOST} ^(www\.)?(.*)$ [NC] 
RewriteCond %{DOCUMENT_ROOT}/%2/%{REQUEST_URI} -f 
RewriteRule ^(robots\.txt|sitemap\.xml)$ /%2/$1 [L] 

# then check www.host/robots.txt 
RewriteCond %{HTTP_HOST} ^(www\.)?(.*)$ [NC] 
RewriteCond %{DOCUMENT_ROOT}/www.%2/%{REQUEST_URI} -f 
RewriteRule ^(robots\.txt|sitemap\.xml)$ /www.%2/$1 [L] 

# finally, do nothing and allow the "/robots.txt" request to resolve itself 
+0

你好,你能告诉我什么是你的答案循环预防和它是如何工作的? – momcho

+0

@momcho'RewriteCond%{ENV:REDIRECT_STATUS} 200'行检查是否有内部重定向(如果有一个,则状态= 200,否则该env变量为空)。如果是这样,请通过请求URI并不做任何事情。当场结束全部重写。 –

+0

谢谢你的回答!配置工作正常。我唯一不理解的是为什么有可能有内部重定向?你能给个例子吗?我想在每个RewriteCond块的顶部放置以下'RewriteCond%{REQUEST_URI}^/(robots \ .txt | sitemap \ .xml)$',以确保对robots.txt或sitemap.xml的请求。 。 – momcho