cors跨域 nginx 配置

2025-03-13 0 75

cors跨域 nginx 配置

在现代Web开发中,跨域资源共享(CORS)是一个常见的问题。当一个资源试图从不同源请求另一个资源时,浏览器出于安全考虑会阻止这种请求,除非服务器明确允许。Nginx作为一款高性能的HTTP和反向代理服务器,可以通过配置来解决CORS问题。

1. 简单解决方案

最简单的解决方案是直接在Nginx的location块中添加CORS相关的响应头。这适用于所有请求都允许跨域访问的场景。

nginx
server {
    listen 80;
    server_name example.com;</p>

<pre><code>location / {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept, Authorization';

    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Content-Length' 0;
        return 204;
    }

    proxy_pass http://backend_server;
}

}

2. 基于域名白名单的配置

为了提高安全性,可以只允许特定域名的跨域请求。这样可以防止恶意网站利用跨域漏洞。

nginx
map $http<em>origin $cors</em>allow<em>origin {
    default "";
    "https://example.com" "$http</em>origin";
    "https://test.example.com" "$http_origin";
}</p>

<p>server {
    listen 80;
    server_name example.com;</p>

<pre><code>location / {
    set $allow_origin "";

    if ($cors_allow_origin) {
        set $allow_origin $cors_allow_origin;
    }

    add_header 'Access-Control-Allow-Origin' $allow_origin;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept, Authorization';

    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Content-Length' 0;
        return 204;
    }

    proxy_pass http://backend_server;
}

}

3. 使用第三方模块

除了直接配置外,还可以使用Nginx的第三方模块ngx_http_headers_more_module来简化CORS配置。需要确保Nginx已经安装了这个模块。

nginx
server {
    listen 80;
    server_name example.com;</p>

<pre><code>location / {
    more_set_headers 'Access-Control-Allow-Origin: $http_origin';
    more_set_headers 'Access-Control-Allow-Methods: GET, POST, OPTIONS';
    more_set_headers 'Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization';

    if ($request_method = 'OPTIONS') {
        more_set_headers 'Access-Control-Max-Age: 1728000';
        more_set_headers 'Content-Type: text/plain charset=UTF-8';
        more_set_headers 'Content-Length: 0';
        return 204;
    }

    proxy_pass http://backend_server;
}

}

以上三种方法可以根据实际需求选择使用。种适合快速开发阶段,第二种适合生产环境以增强安全性,第三种则为喜欢简洁配置的朋友提供了另一种思路。

Image

1. 本站所有资源来源于用户上传和网络,因此不包含技术服务请大家谅解!如有侵权请邮件联系客服!cheeksyu@vip.qq.com
2. 本站不保证所提供下载的资源的准确性、安全性和完整性,资源仅供下载学习之用!如有链接无法下载、失效或广告,请联系客服处理!
3. 您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容资源!如用于商业或者非法用途,与本站无关,一切后果请用户自负!
4. 如果您也有好的资源或教程,您可以投稿发布,成功分享后有积分奖励和额外收入!
5.严禁将资源用于任何违法犯罪行为,不得违反国家法律,否则责任自负,一切法律责任与本站无关

源码下载