【问题标题】:RewriteCond in .htaccess to search robots.txt and sitemap.xml in domain subfolder.htaccess 中的 RewriteCond 以在域子文件夹中搜索 robots.txt 和 sitemap.xml
【发布时间】:2013-11-28 06:12:56
【问题描述】:

我想编写一个重写器来搜索与带有或不带有 www 的域名匹配的子文件夹中的 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
  • Else如果有文件匹配子文件夹 %{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]

感谢您的帮助!

【问题讨论】:

    标签: apache .htaccess mod-rewrite


    【解决方案1】:

    试试:

    # 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
    

    【讨论】:

    • 你好,你能告诉我你的答案中的循环预防是什么以及它是如何工作的?
    • @momcho RewriteCond %{ENV:REDIRECT_STATUS} 200 行检查是否存在内部重定向(如果有,则状态将 = 200,否则 env 变量为空)。如果是这样,则通过请求 URI 并且什么也不做。即刻结束所有重写。
    • 感谢您的回答!配置工作正常。我唯一不明白的是为什么可以进行内部重定向?能给我举个例子吗?我想将以下RewriteCond %{REQUEST_URI} ^/(robots\.txt|sitemap\.xml)$ 放在每个 RewriteCond 块的顶部,以确保 robots.txt 或 sitemap.xml 上的请求...
    • @momcho 这是因为重写引擎循环直到无事可做。
    • 感谢您的解释!
    猜你喜欢
    • 2015-06-04
    • 2013-11-11
    • 1970-01-01
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-14
    相关资源
    最近更新 更多