巧用Nginx配置解决跨域问题

yizhihongxing


巧用Nginx配置解决跨域问题

页面nginx配置

1,前端页面放在域名根目录,比如,http://www.xuecheng.com/ ,对应的nginx配置:

#门户
        location / {
            alias  D:/Z_lhy/SpringCloud/xuecheng_online/www/xc-ui-pc-static-portal/;
            index  index.html;
        }

页面目录:

巧用Nginx配置解决跨域问题

接口nginx配置

2,前端请求接口路径,在域名后面加一个目录

url : "http://www.xuecheng.com/api/auth/oauth/token",//发送请求的地址 
function login(){
        var uname = $("#username").val();
        var pwd = $("#password").val();
        
         $.ajax({
            url : "http://www.xuecheng.com/api/auth/oauth/token",//发送请求的地址 
            type: "post",
            dataType: "json",
            data : "username="+uname+"&password="+pwd+"&grant_type=password",
            beforeSend:function (request) {
                 // 如果后台没有跨域处理,这个自定义
                 request.setRequestHeader("Authorization","Basic RG9jV2ViQXBwOjEyMzQ1Ng==");
                 // 禁用按钮,防止重复提交
                 $("#submit").attr({ disabled: "disabled" });
            },
            error : function() {
                alert("error occured!!!");//请求失败时弹出的信息
            },
            success : function(data) {//返回的信息展示出来
                alert(JSON.stringify(data))
            }
        });
    };

nginx 对api接口配置

location /api/ {
            add_header 'Access-Control-Allow-Origin' $http_origin;
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
            add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
            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://apiserver/; 
           proxy_set_header Host $host;
           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 $scheme;
           proxy_connect_timeout 5;
        }
        

其中的

$http_origin

$http_origin并不是nginx的内置参数,nginx支持取自定义的参数值,$http_XXX这个格式是nginx取请求中header的XXX的值的。这里取的是origin,而一般跨域请求都会将请求的来源放在origin中(浏览器会往跨域请求的header上面加origin这个header)。

巧用Nginx配置解决跨域问题

 

 

这样配置的话,前端页面在域名下:www.xuecheng.com,而访问的接口则是www.xuecheng.com/api/xxx ,这样就不存在跨域问题了,

其实nginx不配置  Access-Control-Allow-Origin也没事,因为前后端在一个域下了。

注意事项

如果你前后端访问存在跨域问题,而且你需要使用cookie,后端要想获取到前端携带过来的cookie,前后端都要做配置:

前端:

var xhr = new XMLHttpRequest()
xhr.withCredentials = true
xhr.open('GET', 'http://localhost:8888/', true)
xhr.send(null)

后端:

Access-Control-Allow-Origin: http://www.abc.com(这里必须域名不能是*)
Access-Control-Allow-Credentials: true

完整nginx配置

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;
    
    #微服务网关
    upstream apiserver{
        server 127.0.0.1:50101;
    }

    server {
        listen       80;
        server_name  www.xuecheng.com;
        
        ssi on;
        ssi_silent_errors on;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;
        
        #门户
        location / {
            alias  D:/Z_lhy/SpringCloud/xuecheng_online/www/xc-ui-pc-static-portal/;
            index  index.html;
        }
        #location  / {
        #   root /neworiental/www/jiaofu;
        #   index index.html;
        #   try_files $uri /index.html;
        #}

        # proxy_pass末尾有/,请求地址:http://localhost/api/test,转发地址:http://127.0.0.1:8000/test
        location /api/ {
            add_header 'Access-Control-Allow-Origin' $http_origin;
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
            add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
            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://apiserver/; 
           proxy_set_header Host $host;
           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 $scheme;
           proxy_connect_timeout 5;
        }
        
        location ^~ /openapi/auth/ {
             proxy_pass http://apiserver/auth/;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

参考:

正确的Nginx跨域配置:https://blog.csdn.net/envon123/article/details/83270277

跨域资源共享(CORS)安全性:https://blog.csdn.net/weixin_43964148/article/details/109352413

 

 

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:巧用Nginx配置解决跨域问题 - Python技术站

(0)
上一篇 2023年4月13日
下一篇 2023年4月13日

相关文章

  • Nginx 实现灰度发布的三种方法总结

    下面我将对“Nginx 实现灰度发布的三种方法总结”的完整攻略进行详细讲解。该攻略包含以下内容: 一、什么是灰度发布 灰度发布是指在生产环境中,只对部分用户或部分功能实施新版本的发布。它可以让新版本在一部分用户或功能中较为安全地进行测试和验证,避免出现大规模的故障和影响到所有用户。 二、Nginx实现灰度发布的三种方法 1. 根据请求头实现灰度发布 该方法是…

    Nginx 2023年5月16日
    00
  • centos 7下nginx搭建流媒体服务器【动态添加模块】

    1、安装nginx依赖包 yum install gcc gcc-c++ openssl-devel zlib-devel pcre pcre-devel yamdi 2.下载解压nginx_mod_h264_streaming,让nginx支持flv,mp4流播放 wget http://h264.code-shop.com/download/nginx_…

    Nginx 2023年4月10日
    00
  • 使用Nginx过滤网络爬虫

    原文:https://www.liaoxuefeng.com/article/001509844125769eafbb65df0a04430a2d010a24a945bfa000   现在的网络爬虫越来越多,有很多爬虫都是初学者写的,和搜索引擎的爬虫不一样,他们不懂如何控制速度,结果往往大量消耗服务器资源,导致带宽白白浪费了。 其实Nginx可以非常容易地根…

    Nginx 2023年4月9日
    00
  • nginx 不记录指定类型日志

        在nginx的服务器中,一些图片或者css的访问日志用处不大的,我们可以不记录这类的日志。 使用 access_log off  来关闭日志记录。 我们也可以对这类型的文件指定浏览器的缓存时间。 使用 expires 1d;  指定缓存时间。 d是天数的单位。 h是小时的单位。 server{ listen 80; server_name bbs.c…

    Nginx 2023年4月11日
    00
  • 在Windows 环境下使用 Nginx 搭建 HTTP文件服务器 实现文件下载 全步骤(详细)

    HOW TO USE NGINX TO BUILD A FILE SERVER   WHAT IS THE NGINX ? “Nginx 是一款轻量级的 HTTP 服务器,采用事件驱动的异步非阻塞处理方式框架,这让其具有极好的 IO 性能,时常用于服务端的反向代理和负载均衡。 它是由俄罗斯人 伊戈尔·赛索耶夫为俄罗斯访问量第二的 Rambler.ru 站点开…

    Nginx 2023年4月13日
    00
  • Nginx基本优化一

    NGINX基本优化 更改nginx服务默认用户优化nginx进程对应配置优化绑定不同的nginx进程到不同cpu,nginx事件处理模型优化,采用epoll模型调整优化单个worker进程并发连接数配置nginx worker进程最大打开文件数优化服务器域名的hash表大小开启高效文件传输模式sendfile,设置tcp_nopush参数优化nginx连接参…

    Nginx 2023年4月12日
    00
  • 通过Nginx代理转发配置实现跨域的方法(API代理转发)

    接下来我会详细讲解通过Nginx代理转发配置实现跨域的方法。这种方法通常用于解决前端应用在访问不同域的API服务时会存在的跨域问题。 简介 跨域是指浏览器从一个域名的网页去请求另一个域名的资源,这里的域名可以理解为协议、主机名、端口号的组合。通常情况下,浏览器限制了脚本中发起跨域HTTP请求。这种安全机制可以有效的防止一些跨站攻击,并保证用户的安全。但是在前…

    Nginx 2023年5月16日
    00
  • 一、基于hadoop的nginx访问日志分析—解析日志篇

    前一阵子,搭建了ELK日志分析平台,用着挺爽的,再也不用给开发拉各种日志,节省了很多时间。 这篇博文是介绍用python代码实现日志分析的,用MRJob实现hadoop上的mapreduce,可以直接放到hadoop集群上运行。 mrjob可以让我们使用Python编写MapReduce运算,并在多个不同平台运行,你可以: 使用纯python编写multi-…

    Nginx 2023年4月10日
    00
合作推广
合作推广
分享本页
返回顶部