【问题标题】:Apache/Nginx: proxy POST requests to remote server, handle OPTIONS requests locallyApache/Nginx:代理 POST 请求到远程服务器,在本地处理 OPTIONS 请求
【发布时间】:2011-06-27 01:25:03
【问题描述】:

我正在尝试将 Apache 配置为远程服务器的代理,以允许使用 CORS 进行跨域 AJAX。为此,我需要 Apache 响应 2 个 HTTP 动词,如下所示:

  1. 选项: 使用一些简单的 HTTP 标头响应这个 CORS 的“飞行前”请求。我想到这可能是一个简单的 CGI 脚本 (options.pl)。

  2. 发布: 将所有 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>

【问题讨论】:

    标签: apache proxy nginx cors


    【解决方案1】:

    这是我使用 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;
        }
    }
    

    【讨论】:

    • 你是如何安装 more_set_headers 的,因为 nginx 是通过安装程序安装在我的服务器上的
    【解决方案2】:

    你现在可以使用我的 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;
            }
        }
    } 
    

    【讨论】:

      猜你喜欢
      • 2020-06-15
      • 2010-09-18
      • 2013-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-03
      • 1970-01-01
      相关资源
      最近更新 更多