apache - robots.txt 和 htaccess(而 CMS 位于子文件夹中)

标签 apache .htaccess mod-rewrite robots.txt xml-sitemap

我的 CMS 位于一个子文件夹中,因此我通过 .htaccess 转发所有内容。对 cms 有好处,下面的代码片段可以正常工作,但对 robots.txt 之类的文件不利,这些文件必须存储在网络根目录中(例如 https://domain.xyz/robots.txt).如果我调用该 URL,浏览器和爬虫将(当然)转发到 https://domain.xyz/TEST

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{HTTPS} !=on
    RewriteRule ^ https://domain.xyz%{REQUEST_URI} [L,R=301]

    RewriteCond %{HTTP_HOST} !^domain\.xyz$ [NC]
    RewriteRule ^ https://domain.xyz/TEST [L,R=301]

    RewriteCond %{REQUEST_URI} !^/TEST
    RewriteRule ^ https://domain.xyz/TEST [L,R=301]
</IfModule>

所以我必须跳过那个文件,然后我会添加

RewriteCond %{THE_REQUEST} !/(robots\.txt|sitemap\.xml)\s [NC]

对于 RewriteRule 之前的文件 robots.txt 和 sitemap.xml,但它不起作用。怎么了?有人可以帮我吗?谢谢。

最佳答案

可以说,这不是“转发”,而是“重定向”,如外部重定向转发 更常用于描述内部重写(URL 不变)。

but bad for files like robots.txt, which have to be stored in the web root

不一定。它们不需要存储在网络根目录中(并从中访问)。在请求 robots.txt、XML 站点地图和类似文件时,Google 和其他搜索引擎会遵循重定向。来自Google Docs for robots.txt - "Handling of errors and HTTP status codes" :

3xx (redirection)
Google follows at least five redirect hops as defined by RFC 1945 and then stops and treats it as a 404 for the robots.txt.

但是,如果您愿意,您仍然可以包含一个异常,但是您的正则表达式中有一个错误...

RewriteCond %{THE_REQUEST} !/(robots\.txt|sitemap\.xml)\s [NC]

您在 CondPattern 的末尾有一个错误的 \s(字面 空格 字符) - 所以它永远不会匹配并且 < em>condition 总是成功的。也许您打算编写 $(字符串结尾 anchor )?您还缺少字符串开头 anchor 。

比如应该是:

RewriteCond %{THE_REQUEST} !^/(robots\.txt|sitemap\.xml)$ [NC]

或者,在您现有的规则之前包含一个积极的匹配规则,以防止在请求这些文件之一时发生任何以后的规则(即重定向) :

# Prevent further processing if "robots.txt" or "sitemap.xml" requested
RewriteRule ^(robots\.txt|sitemap\.xml)$ - [NC,L]
RewriteRule ^ https://domain.xyz/TEST [L,R=301]

由于 TEST 是一个物理目录,您应该在重定向的 URL 后附加一个斜杠,即。 /TEST/,否则 Apache (mod_dir) 将在尾部斜杠后附加 第二个 重定向。

您需要在测试前清除浏览器缓存,因为 301(永久)重定向已被浏览器缓存。

关于apache - robots.txt 和 htaccess(而 CMS 位于子文件夹中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72207333/

相关文章:

php - .htaccess - 传递 URI 参数而不是目录列表 PHP

php - 获取 服务器遇到内部错误或配置错误,无法完成您的请求

apache - Debian 8 - SSL 证书不工作

windows - Apache(WAMP)问题 : “AH00404: Child: Unable to read socket data from parent”

php - ubuntu 20.04 apache2 - php 文件下载

apache - 使用 .htaccess 通配符 301 重定向

java - 使用 Selenium Webdriver 连接远程数据库并通过 eclipse 从本地机器运行测试用例

PHP 代码确定用户是否被 301 重定向到我的网站

regex - 重定向所有子目录但不重定向父目录

apache - Apache Tajo 和 Apache hive 之间的实际区别是什么