Apache/Nginx:将POST请求代理到远程服务器,本地处理OPTIONS请求

3
我正在尝试配置Apache作为代理服务器,以允许使用CORS进行跨域AJAX。为了实现这一点,我需要Apache响应两个HTTP动词,如下所示:
  1. OPTIONS:用一些简单的HTTP标头回应此CORS“预检”请求。我考虑使用一个简单的CGI脚本(options.pl)。

  2. POST:将所有POST请求代理到远程服务器,但添加Access-Control-Allow-Origin“*”标头以允许跨域请求发生。

我可以独立地实现这两个要求,但无法同时配置Apache。问题在于当ProxyPass和ProxyPassReverse被配置后,OPTIONS请求不再命中CGI脚本,而是被代理到远程服务器。
我的当前配置如下。如果可能的话,我希望通过纯的Web服务器解决这个问题,例如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>
2个回答

4
这是我使用Nginx解决它的方法。请注意,我正在使用Headers More模块,这要求我从源代码编译Nginx
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;
    }
}

您是如何安装more_set_headers的?因为nginx是从安装程序中安装在我的服务器上的。 - Hunt

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;
        }
    }
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接