作为mod_rewrite apache条件的标头的动态日期时间值



我有一个目录'/output/",其中包含只有在浏览器发送了值为"tst"的标头("头"(时才可访问的图像。它在.htaccess中使用mod_rewrite通过这些行来工作。.htaccess文件位于"中/输出/':

RewriteEngine On
RewriteCond "%{HTTP:testheader}" !tst
RewriteRule ^ - [F]

为了测试它,我在我的网络服务器上运行以下代码:

<!DOCTYPE html>
<head>
<script>
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob'; //so you can access the response like a normal URL
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
var img = document.createElement('img');
img.src = URL.createObjectURL(xhr.response);
document.body.appendChild(img);
}
};
xhr.open('GET', 'https://www.example.com/output/down.png', true);
xhr.setRequestHeader('testheader','tst');
xhr.send();
</script>
</head>
<body></body>
</html>

当更改"testheader"的值时,这将验证并运行良好!

现在我想更进一步,创建一个更动态的解决方案,我想给"testheader"提供一个动态日期-时间值YYYYMMDD,例如"20220817"。如果发送的标头小于此整数,则应禁止发送。

阅读手册

https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html

https://harrybailey.com/2015/08/htaccess-redirects-based-on-date-and-time/

我想出了这个:

RewriteEngine On
RewriteCond %{HTTP:testheader} <%{TIME_YEAR}%{TIME_MON}%{TIME_DAY}
RewriteRule ^ - [F]

现在有了上面的代码,我设置标题如下:

xhr.setRequestHeader('testheader','20220817'); //should be changed to current date

但无论我设定了什么日期,现在图像都在/output/'总是被阻止。

也许我在.htaccess中的语法是错误的?我不确定是否允许我在RewriteCond中的等式右侧使用"%{TIME_YEAR}%{IME_MON}%}TIME_DAY}"。

希望你们中的一个有一个绝妙的解决方案!

解决方案:

它就在手册第5节下。https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html

使用带有-strmatch的"expr",它会按请求执行操作。有了这个.htaccess,问题就解决了:

RewriteEngine On
RewriteCond expr "! %{HTTP:testheader} -strmatch '%{TIME_YEAR}%{TIME_MON}%{TIME_DAY}'"
RewriteRule ^ - [F]

最新更新