【问题标题】:Is there a way to treat ajax requests different than user requests in .htaccess?有没有办法处理 ajax 请求与 .htaccess 中的用户请求不同?
【发布时间】:2022-01-04 09:17:56
【问题描述】:

假设我有/secret/example.php
在我的 .htaccess 文件中,我想将请求重写为 /secret/home.html 使用

RewriteRule secret /home.html

但是现在当我尝试使用来自example.js 的ajax 访问/secret/example.php

var xhr = new XMLHttpRequest();
xhr.open('GET', '/secret/example.php', true);
xhr.onload = function(){
  console.log(xhr.responseText);
}
xhr.send();

它也被重定向并且不起作用。

有没有办法我只能重写用户提出的请求(通过在搜索栏中输入www.example.com/secret)并仍然允许 ajax 访问文件?

【问题讨论】:

  • 您可以简单地在您评估的 ajax 请求中设置一个附加标头。

标签: javascript php ajax .htaccess


【解决方案1】:

如果您在 xhr 请求中设置附加标头是可能的:xhr.setRequestHeader("VIAXHR", "true");

然后在 .htaccess 中是这样的:

RewriteCond %{HTTP:VIAXHR} !^true$
RewriteRule secret /home.html

【讨论】:

    【解决方案2】:

    在 RewriteRule 之前使用 RewriteCond

    RewriteCond documentation

    类似这样的:

    RewriteCond %{REQUEST_URI} !^/secret/example.php$
    RewriteRule secret /home.html
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-13
      • 1970-01-01
      • 2019-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多