nginx跨域访问配置的几种方法实现

2025-12-08 20:50

本文主要是介绍nginx跨域访问配置的几种方法实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《nginx跨域访问配置的几种方法实现》本文详细介绍了Nginx跨域配置方法,包括基本配置、只允许指定域名、携带Cookie的跨域、动态设置允许的Origin、支持不同路径的跨域控制、静态资源跨域以及...

一、基本跨域配置

在 nginx 的 location 块中添加以下内容:

location /api/ {
    add_header 'Access-Control-Allow-Origin' '*' always;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
    add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept, Authorization' always;
 
    # 处理预检请求(OPTIONS)
    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;
}

说明:

  • Access-Control-Allow-Origin:允许哪些域访问,* 表示所有域。
  • Access-Control-Allow-Methods:允许的 HTTP 方法。
  • Access-Control-Allow-Headers:允许的请求头。
  • OPTIONS 方法用于处理 CORS 预检请求,返回 204 No Content。

二、只允许指定域名跨域

如果只允许某个域(如 https://www.example.com)跨域:

add_header 'Access-Control-Allow-Origin' 'https://www.example.com' always; 

三、完整示例

假设你有一个前端(端口 8080)和后端(端口 8000),nginx 代理 /api/ 到后端:

server {
    listen 80;
    server_name your.domain.com;
 
    location /api/ {
        proxy_pass http://127.0.0.1:8000;
        add_header 'Access-Control-Allow-Origin' '*' always;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
        add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept, Authorization' always;
 
        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;
        }
    }
}

四、配置后重载 nginx

每次修改配置后,记得重载 nginx:

nginx -s reload 

五、注意事项

  • 如果后端也设置了 CORS,可能会有冲突,建议只在一个地方设置。
  • 如果需要携带 cookie,Access-Control-Allow-Origin 不能为 *,必须指定具体域名,并加上 Access-Control-Allow-Credentials: true

六、支持携带 Cookie 的跨域配置

如果你需要前端跨域请求时携带 cookie(如登录态),CORS 需要特殊配置:

  1. Access-Control-Allow-Origin 不能为 *,必须指定具体的域名。
  2. 需要加上 Access-Control-Allow-Credentials: true

示例:

location /api/ {
    proxy_pass http://127.0.0.1:8000;
 
    add_header 'Access-Control-Allow-Origin' 'https://www.example.com' always;
    add_header 'Access-Control-Allow-Credentials' 'true' always;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
    add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept, Authorization' always;
 
    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;
    }
}

前端请求时需要设置:

fetch('https://api.example.com/api/', {
  credentials: 'include', // 允许携带 cookie
  // 其他参数
})

七、根据请求头动态设置允许的 Origin

有时你希望根据请求头 Origin 动态设置允许的域名,可以用 nginx 的变量:

location /api/ {
    proxy_pass http://127.0.0.1:8000;
 
    if ($http_origin ~* "^https://(www\.example\.com|other\.domain\.com)$") {
        add_header 'Access-Control-Allow-Origin' "$http_origin" always;
        add_header 'Access-Control-Allow-Credentials' 'true' always;
    }
 
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
    add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept, Authorization' always;
 
    # 处理预检请求
    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;
    }
}

八、常见问题排查

  1. add_header 不生效?

    • 确认 always 关键字已加上。
    • 确认没有被其他配置覆盖。
    • 确认 location 块没有被其他 server/location 块覆盖。
  2. OPTIONS 请求未返回 204?

    • 检查 if 语句是否正确。
    • 检查是否被后端拦截。
  3. 前端报错:CORS header ‘Access-Control-Allow-Origin’ missing?

    • 检查响应头是否包含该字段。
    • 用浏览器开发者工具 Network 检查响应头。
  4. 携带 cookie 时跨域失败?

    • 确认 Access-Control-Allow-Origin 不是 *,而是具体域名。
    • 确认 Access-Control-Allow-Credentials: true 已设置。
    • 前端 fetch/axIOS 需配置 credentials。

九、nginx 跨域配置模板(推荐)

可以将以下内容作为通用模板:

location /api/ {
    proxy_pass http://backend-server;
 
编程    # 支持跨域
    set $cors '';
    if ($http_origin ~* '^https://(www\.example\.com|other\.domain\.com)$') {
        set $cors 'true';
    }
 
    if ($cors = 'true') {
        add_header 'Access-Control-Allow-Origin' "$http_origin" always;
        add_header 'Access-Control-Allow-Credentials' 'true' always;
    }
 
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
    add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept, Authorization' always;
 
    # 预检处理
    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;
    }
}

十、针对不同路径/接口做跨域控制

有时你只希望对部分接口(如 /api/)开放跨域,对其他接口(如 /admin/)不开放,可以这样配置:

server {
    listen 80;
    server_name your.domain.com;
 
    # 只对 /api/ 开放跨域
    location /api/ {
        proxy_pass http://backend-api;
        add_header 'Access-Control-Allow-Origin' '*' always;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
        add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept, Authorization' always;
 
        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;
        }
    }
 
    # /admin/ 不开放跨域
    location /admin/ {
        proxy_pass http://backend-admin;
        # 不添加跨域相关 header
    }
}

十一、静态资源跨域(如图片、字体、JS/CSS)

如果你希望静态资源(如图片、字体文件等)可以被其他域引用,需为静态资源 location 添加 CORS 响应头:

location /static/ {
    root /var/www/html;
    add_header 'Access-Control-Allow-Origin' '*' always;
    add_header 'Access-Control-Allow-Methods' 'GET, OPTIONS' always;
    add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept' always;
}

注意:如果你希望字体文件可被第三方引用,必须加上 Access-Control-Allow-Origin,否则会有跨域问题。

十二、根据请求方法细分 CORS 策略

有时你希望 GET/POST/PUT/DELETE 允许跨域,而 PATCH 不允许,可以这样写:

location /api/ {
    proxy_pass http://backend-server;
 
    if ($request_method ~* "GET|POST|PUT|DELETE|OPTIONS") {
        add_header 'Access-Control-Allow-Origin' '*' always;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
        add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept, Authorization' always;
    }
 
    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;
    }
}

十三、反向代理多后端的跨域配置

如果 nginx 代理多个后端(如 /api1//api2/),每个后端都需要跨域:

location /api1/ {
    proxy_pass http://backend1;
    add_header 'Access-Control-Allow-Origin' '*' always;
    # ...同上
}
 
location /api2/ {
    proxy_pass http://backend2;
    ahttp://www.chinasem.cndd_header 'Access-Control-AlChina编程low-Origin' '*' always;
    # ...同上
}

十四、nginx 1.7.5 及以上版本的 always 参数

确保你用的 nginx 版本支持 always 参数,否则有些 header 在 4xx/5xx 状态下不会返回。

十五、安全建议

  1. 生产环境不要使用 *,要指定具体域名。
  2. 不建议在 / 根路径全局添加 CORS,容易引发安全隐患。
  3. 如需支持多域名跨域,推荐用变量和正则动态判断。
  4. 如果接口涉及敏感数据,务必开启认证和 HTTPS。

十六、调试技巧

  • 用 Chrome/Firefox 开发者工具的 Network 面板查看 Response Headers,确认 CORS 头是否正确返回。
  • 使用 curl -i 命令直接发起跨域请求,检查响应头。
  • 检查 nginx 日志(access.log 和 error.log)排查问题。

十七、完整多场景配置模板

server {
    listen 80;
    server_name your.domain.com;
 
    # 静态资源
    location /static/ {
        root /var/www/html;
        add_header 'Access-Control-Allow-Origin' '*' always;
    }
 
    # API1 跨域
    location /api1/ {
        proxy_pass http://backend1;
        add_header 'Access-Control-Allow-Origin' 'https://www.a.com' always;
        add_header 'Access-Control-Allow-Credentials' 'true' always;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
        add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept, Authorization' always;
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain charset=UTF-8';
            add_header 'phpContent-Length' 0;
            return 204;
        }
    }
 
    # API2 跨域
    location /api2/ {
        proxy_pass http://backend2;
        add_header 'Access-Control-Allow-Origin' 'https://www.b.com' always;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
        add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept, Authorization' always;
        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;
        }
    }
}

到此这篇关于nginx跨域访问配置的几种方法实现的文章就介绍到这了,更多相关nginx跨域访问配置内容请搜索China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程China编程(www.cp编程pcns.com)!

这篇关于nginx跨域访问配置的几种方法实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1156389

相关文章

Nginx 访问控制的多种方法

《Nginx访问控制的多种方法》本文系统介绍了Nginx实现Web访问控制的多种方法,包括IP黑白名单、路径/方法/参数控制、HTTP基本认证、防盗链机制、客户端证书校验、限速限流、地理位置控制等基... 目录一、IP 白名单与黑名单1. 允许/拒绝指定IP2. 全局黑名单二、基于路径、方法、参数的访问控制

springboot3.x使用@NacosValue无法获取配置信息的解决过程

《springboot3.x使用@NacosValue无法获取配置信息的解决过程》在SpringBoot3.x中升级Nacos依赖后,使用@NacosValue无法动态获取配置,通过引入SpringC... 目录一、python问题描述二、解决方案总结一、问题描述springboot从2android.x

C#高效实现在Word文档中自动化创建图表的可视化方案

《C#高效实现在Word文档中自动化创建图表的可视化方案》本文将深入探讨如何利用C#,结合一款功能强大的第三方库,实现在Word文档中自动化创建图表,为你的数据呈现和报告生成提供一套实用且高效的解决方... 目录Word文档图表自动化:为什么选择C#?从零开始:C#实现Word文档图表的基本步骤深度优化:C

Nginx服务器部署详细代码实例

《Nginx服务器部署详细代码实例》Nginx是一个高性能的HTTP和反向代理web服务器,同时也提供了IMAP/POP3/SMTP服务,:本文主要介绍Nginx服务器部署的相关资料,文中通过代码... 目录Nginx 服务器SSL/TLS 配置动态脚本反向代理总结Nginx 服务器Nginx是一个‌高性

Python中Request的安装以及简单的使用方法图文教程

《Python中Request的安装以及简单的使用方法图文教程》python里的request库经常被用于进行网络爬虫,想要学习网络爬虫的同学必须得安装request这个第三方库,:本文主要介绍P... 目录1.Requests 安装cmd 窗口安装为pycharm安装在pycharm设置中为项目安装req

Qt实现对Word网页的读取功能

《Qt实现对Word网页的读取功能》文章介绍了几种在Qt中实现Word文档(.docx/.doc)读写功能的方法,包括基于QAxObject的COM接口调用、DOCX模板替换及跨平台解决方案,重点讨论... 目录1. 核心实现方式2. 基于QAxObject的COM接口调用(Windows专用)2.1 环境

MySQL查看表的历史SQL的几种实现方法

《MySQL查看表的历史SQL的几种实现方法》:本文主要介绍多种查看MySQL表历史SQL的方法,包括通用查询日志、慢查询日志、performance_schema、binlog、第三方工具等,并... 目录mysql 查看某张表的历史SQL1.查看MySQL通用查询日志(需提前开启)2.查看慢查询日志3.

MySQL底层文件的查看和修改方法

《MySQL底层文件的查看和修改方法》MySQL底层文件分为文本类(可安全查看/修改)和二进制类(禁止手动操作),以下按「查看方法、修改方法、风险管控三部分详细说明,所有操作均以Linux环境为例,需... 目录引言一、mysql 底层文件的查看方法1. 先定位核心文件路径(基础前提)2. 文本类文件(可直

Java实现字符串大小写转换的常用方法

《Java实现字符串大小写转换的常用方法》在Java中,字符串大小写转换是文本处理的核心操作之一,Java提供了多种灵活的方式来实现大小写转换,适用于不同场景和需求,本文将全面解析大小写转换的各种方法... 目录前言核心转换方法1.String类的基础方法2. 考虑区域设置的转换3. 字符级别的转换高级转换

使用Python实现局域网远程监控电脑屏幕的方法

《使用Python实现局域网远程监控电脑屏幕的方法》文章介绍了两种使用Python在局域网内实现远程监控电脑屏幕的方法,方法一使用mss和socket,方法二使用PyAutoGUI和Flask,每种方... 目录方法一:使用mss和socket实现屏幕共享服务端(被监控端)客户端(监控端)方法二:使用PyA