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

py49o6xq  于 2022-11-16  发布在  Apache
关注(0)|答案(1)|浏览(137)

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

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

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

<!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}%{TIME_MON}%{TIME_DAY}'。
希望你们中的一个有一个辉煌的解决方案!

pod7payv

pod7payv1#

解决方案:

它就在手册的第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]

相关问题