结合 URL 映射和 Access-Control-Allow-Origin:*

结合 URL 映射和 Access-Control-Allow-Origin:*

我正在将旧横幅系统迁移到新系统,因此我想将旧横幅系统的 URL 重写为新系统。我通过 AJAX 请求加载横幅,因此我需要将 设置Access-Control-Allow-Origin*

我有以下VirtualHost配置:

<VirtualHost *:80>
    ServerAdmin [email protected]
    ServerName banner.studenten.net

    # we want to allow XMLHTTPRequests
    Header set Access-Control-Allow-Origin "*"

    RewriteEngine on
    RewriteMap bannersOldToNew txt:/home/user/banner.studenten.net/banner-studenten-net-to-ads-all4students-nl-map

    # check whether a zoneid exists in the query string
    RewriteCond %{QUERY_STRING} ^(.*)zoneid=([1-9][0-9]*)(.*)
    # make sure the requested banner has been mapped
    RewriteCond ${bannersOldToNew:%2|NOTFOUND} !=NOTFOUND
    # rewrite to ads.all4students.nl
    RewriteRule ^/ads/.* http://ads.all4students.nl/delivery/ajs.php?%1zoneid=${bannersOldToNew:%2}%3 [R]
    # else 404 or something

    ErrorLog ${APACHE_LOG_DIR}/banner.studenten.net-error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/banner.studenten.net-access.log combined

</VirtualHost>

我的地图文件/home/user/banner.studenten.net/banner-studenten-net-to-ads-all4students-nl-map包含如下内容:

# oldId newId
140 11
141 12
142 13

根据上述配置我预期以下内容:

GET /ads/ajs.php?zoneid=140 HTTP/1.1
Host: banner.studenten.net

HTTP/1.1 302 Found
...
Access-Control-Allow-Origin: *
Location: http://ads.all4students.nl/delivery/ajs.php?zoneid=11

但我得到的却是以下内容:

GET /ads/ajs.php?zoneid=140 HTTP/1.1
Host: banner.studenten.net

HTTP/1.1 302 Found
...
Location: http://ads.all4students.nl/delivery/ajs.php?zoneid=11

请注意缺少Access-Control-Allow-Origin标头,这意味着 XMLHttpRequest 被拒绝,横幅未显示。关于如何在 Apache 中修复此问题,有什么建议吗?

答案1

我找到了解决这个问题的方法,显然 ApacheHeader set只适用于 2xx 状态代码(基于http://httpd.apache.org/docs/2.0/mod/mod_headers.html#header)为了让访问控制标头在我的配置中工作,我必须输入Header always set

<VirtualHost *:80>
    ...

    # we want to allow XMLHTTPRequests
    Header always set Access-Control-Allow-Origin "*"

    ...

</VirtualHost>

相关内容