2011-02-14 66 views
3

我試圖將Apache配置爲充當遠程服務器的代理,以允許使用CORS的跨域AJAX。要做到這一點,我需要Apache迴應2個HTTP動詞,就像這樣:Apache/Nginx:向遠程服務器請求POST請求,在本地處理OPTIONS請求

  1. 選項: 應對這一CORS「飛行前的」一些簡單的HTTP標頭的請求。我記得這可能是一個簡單的CGI腳本(options.pl)。

  2. POST: 將所有POST請求代理到遠程服務器,但添加Access-Control-Allow-Origin「*」標頭以允許跨域請求發生。

我可以獨立地實現這兩個要求,但我不能配置Apache來執行這兩個要求。問題是當配置ProxyPass和ProxyPassReverse時,OPTIONS請求不再命中CGI腳本,它們被代理到遠程服務器。

我目前的配置如下。我想用純粹的網絡服務器解決方案解決這個問題,例如Apache/Nginx(而不是運行一些應用程序代碼),如果可能的話。

<VirtualHost *:80> 

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ 

    DocumentRoot /var/www 

    <Location "/"> 

     # Disallow all verbs except OPTIONS and POST 
     order deny,allow 
     deny from all 

     # OPTIONS should be handled by a local CGI script 
     <Limit OPTIONS> 
      allow from all 
      Script OPTIONS /cgi-bin/options.pl 
     </Limit> 

     # POST requests are proxied to a remote server 
     <Limit POST> 
      allow from all 
      ProxyPass http://somewhere-else/ 
      ProxyPassReverse http://somewhere-else/ 
      Header add Access-Control-Allow-Origin "*" 
     </Limit> 

    </Location> 
</VirtualHost> 

回答

4

下面是我用Nginx解決它的方法。請注意,我使用的Headers More模塊需要我到compile Nginx from source

location/{ 

    if ($request_method = 'OPTIONS') { 
     more_set_headers 'Access-Control-Allow-Origin: *'; 
     more_set_headers 'Access-Control-Allow-Methods: POST, OPTIONS'; 
     more_set_headers 'Access-Control-Max-Age: 1728000'; 
     more_set_headers 'Content-Type: text/plain; charset=UTF-8'; 

     return 200; 
    } 

    if ($request_method = 'POST') { 
     more_set_headers 'Access-Control-Allow-Origin: *'; 
     proxy_pass http://somewhere-else; 
    } 
} 
+0

你怎麼安裝more_set_headers,如nginx的安裝,從安裝在我的服務器 – Hunt 2012-12-11 09:26:53

4

您現在可以使用我的nginx_cross_origin_module。它支持完整的CORS功能:https://github.com/yaoweibin/nginx_cross_origin_module

例子:

http { 

    cors on; 
    cors_max_age  3600; 
    cors_origin_list unbounded; 
    cors_method_list GET HEAD PUT POST; 
    cors_header_list unbounded; 

    server { 
     listen  80; 
     server_name localhost; 

     location/{ 
      root html; 
      index index.html index.htm; 
     } 
    } 
}