使用 htaccess 由外部 cdn 缓存的日志图像文件名

Log image filename that's cached by external cdn using htaccess

我想在特定的 cdn 缓存我们的图像时记录图像文件名,但我不太明白。现在,我的代码看起来像:

RewriteCond %{HTTP_USER_AGENT} Photon/1.0
RewriteRule ^(.*)$ log.php?image= [L]

即使我将 cdn 缓存设置为“example.jpg”,上面总是将图像记录为“log.php”,我完全不明白为什么。

The above always logs the image as being "log.php" even if I'm making the cdn cache "example.jpg" and I thoroughly don't understand why.

因为在 .htaccess 中,重写引擎循环直到 URL 通过不变(尽管存在 L 标志)并且您的规则也匹配 log.php (你的规则匹配 everything) - 所以这是最终记录的“图像”。 L 标志只是通过重写引擎停止当前 pass

例如:

  1. 请求/example.jpg
  2. 请求重写为log.php?image=example.jpg
  3. 重写引擎重新开始,通过 /log.php?image=example.jpg 到第二遍的开始。
  4. 请求被相同的 RewriteRule 指令重写为 log.php?image=log.php
  5. 重写引擎重新开始,通过 /log.php?image=log.php 到第三遍的开始。
  6. 请求被重写为 log.php?image=log.php(再次)。
  7. URL 在最后一次传递中没有改变 - 处理停止。

您需要创建一个例外,这样 log.php 本身就不会被处理。或者,声明所有非 .php 文件都已处理(而不是 所有 )。或者,如果只处理图像,则只检查图像。

例如:

# Log images only
RewriteCond %{HTTP_USER_AGENT} Photon/1\.0
RewriteRule ^(.+\.(?:png|jpg|webp|gif))$ log.php?image= [L]

记得在正则表达式中反斜杠转义文字点。

或者,

# Log Everything except log.php itself
RewriteCond %{HTTP_USER_AGENT} Photon/1\.0
RewriteCond %{REQUEST_URI} ^/(.+)
RewriteRule !^log\.php$ log.php?image=%1 [L]

在最后一个示例中,%1 指的是前面 CondPattern 中捕获的子模式。我只是这样做的,而不是直接使用 REQUEST_URI 因为你在你的原始日志记录指令中排除了斜杠前缀(即你在请求 /image.jpg 时将 image.jpg 传递给你的脚本).如果你也想记录斜杠前缀,那么你可以省略第二个条件并直接传递REQUEST_URI。例如:

# Log Everything except log.php itself (include slash prefix)
RewriteCond %{HTTP_USER_AGENT} Photon/1.0
RewriteRule !^log\.php$ log.php?image=%{REQUEST_URI} [L]

或者,在 Apache 2.4+ 上,您可以使用 END 标志而不是 L 来强制重写引擎停止并防止进一步通过重写引擎。例如:

RewriteCond %{HTTP_USER_AGENT} Photon/1\.0
RewriteRule (.+) log.php?image= [END]