Nginx处理跨域请求(CORS)

Nginx处理跨域请求(CORS)

使用 Nginx 轻松处理跨域请求(CORS)

在现代 Web 开发中,跨域资源共享(CORS)是一种重要的机制,用于解决浏览器的同源策略限制。CORS 允许服务器声明哪些来源可以访问其资源,从而确保安全性与可用性。本文将介绍如何在 Nginx 中配置跨域访问,并详细解析每个配置项的作用和用法。

什么是 CORS?

CORS(Cross-Origin Resource Sharing)是一种 HTTP 头部机制,允许服务器声明哪些外部域(origin)可以访问其资源。由于安全原因,浏览器通常不允许跨域请求,但通过 CORS,服务器可以显式地允许某些域访问其资源。

为什么需要 CORS?

安全性:保护用户数据,防止恶意网站进行未授权访问。

API 访问:允许前端应用(如 React、Vue.js 等)安全地调用后端 API。

多源共享:在不同的子域、域或协议间共享资源。

https://blog.youkuaiyun.com/qaknar826/article/details/143055093

人资小程序后台服务器配置:

server {
  listen 443 ssl;
	access_log  logs/access.log main;
	server_name hr.abc.com.cn;
	ssl_certificate httpssl/hr.abc.com.cn.pem;
	ssl_certificate_key httpssl/hr.abc.com.cn.key;
	ssl_session_timeout 5m;
	ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4:!DES:!3DES;
	ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
	ssl_prefer_server_ciphers on;
        proxy_ssl_server_name on;
        proxy_ssl_verify off;

    gzip on;
    gzip_static on;     # 需要http_gzip_static_module 模块
    gzip_min_length 1k;
    gzip_comp_level 4;
    gzip_proxied any;
    gzip_types text/plain text/xml text/css;
    gzip_vary on;
    gzip_http_version   1.0; #兼容多层nginx 反代
    gzip_disable "MSIE [1-6]\.(?!.*SV1)";    


       root /home/hrms/www/dist;
    
        location ^~/api/ {
        proxy_pass http://hrms-gateway:9999/; #注意/后缀
        proxy_connect_timeout 60s;
        proxy_read_timeout 120s;
        proxy_send_timeout 120s;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto http;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $http_host;
        # 跨域
        #add_header 'Access-Control-Allow-Origin' 'https://bk.abc.com.cn' always;
        #add_header 'Access-Control-Allow-Origin' 'https://www.abc.com.cn' always;
        add_header 'Access-Control-Allow-Origin' * always;
    }



    # 避免端点安全问题
    if ($request_uri ~ "/actuator"){
	    return 403;
    }
    
 }

在API接口服务器的nginx上配置“add_header ‘Access-Control-Allow-Origin’ * always;”后,浏览器打开页面访问api接口时,Response Headers中会出现 Access-Control-Allow-Origin: * 这一行参数,浏览器访问该api接口时,不在报CORS error

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值