【问题标题】:deliver resource based on html file url calling an asset根据调用资产的 html 文件 url 传递资源
【发布时间】:2018-01-31 18:59:25
【问题描述】:

如果我有一个位于http://sample.com 的 html 文件,并且该 html 文件正在通过 ajax 调用加载到资产中,那么服务器是否可以拦截该资产并交付不同的资产,而无需 html 文件更改 url 或添加 url 参数到资产 ur;?

示例:http://sample.com/index.html?configID=567 有一个使用 ajax 加载的 config.json 文件,如下所示: $.getJSON('config.json', function(data){});

apache 能否知道这个 config.json 文件正在由一个 html 文件请求,该文件的 url 参数为 configID=567 并从 config567.json 而不是 config.json 传回响应?

我无法修改 html 文件中的 javascript 以读取 $.getJSON('config.json?configID=567', function(data){});,所以我只想在服务器端进行修改。

如果有针对此问题的 php 解决方案,而无需将 html 文件更改为 php 文件,我也会运行 php。

【问题讨论】:

  • 看看 config.json 请求中的 referer 标头 ($_SERVER['HTTP_REFERER']) 怎么样,它应该告诉您触发请求的页面的 url。

标签: php ajax apache redirect


【解决方案1】:

您似乎正在寻找 Apache 中基于Referer 的重写。实现细节可能对您有所不同,但您可以尝试根据 ID 获取不同的文件:

RewriteEngine On
RewriteCond %{HTTP_REFERER} configID=(\d+)$
RewriteRule ^config.json$ configs/config-%1.json

%1 部分指的是RewriteCond 行中的括号组。

或者,您可以启用 json 文件类型的 PHP 处理并在 php 中实现逻辑:

// config.json
<?php
$id = $_GET['configID'];
header('Content-Type: application/json');
echo get_config_from_database_by_id($id);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 2022-11-11
    • 2021-09-29
    相关资源
    最近更新 更多