Mod-Rewrite

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

  • April 12, 2012

我正在將舊橫幅系統遷移到新橫幅系統,因此我想將舊橫幅系統的 URL 重寫為新橫幅系統。我通過 AJAX 請求載入橫幅,因此我需要將Access-Control-Allow-Origin其設置為*.

我有以下VirtualHost配置:

<VirtualHost *:80>
   ServerAdmin webmaster@all4students.nl
   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 中解決此問題的任何建議?

我找到了解決這個問題的方法,顯然 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>

引用自:https://serverfault.com/questions/378564