首页 > 系统相关 >巧用Nginx配置解决跨域问题

巧用Nginx配置解决跨域问题

时间:2023-04-11 10:12:18浏览次数:48  
标签:Control http 跨域 header Access Nginx add proxy 巧用

页面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配置

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)。

 

 

这样配置的话,前端页面在域名下: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

 

标签:Control,http,跨域,header,Access,Nginx,add,proxy,巧用
From: https://www.cnblogs.com/lihaoyang/p/17303937.html

相关文章

  • Linux环境下nginx安装详细教程,一步步装上nginx
    本人安装Nginx环境为:CentOS7.9 下载安装包下载Nginx安装包Linux版:Nginx官网下载:https://nginx.org/en/download.html下载Stableversion(即稳定版) 上传安装包将压缩包放入系统: 解压:tar-zxvfnginx-1.22.1.tar.gz解压成功: 编译安装执行./configure配置命令:这里提示./config......
  • Nginx upstream采集
    因为nginx无论是开启模块还是添加模块都需要重新编译,我们首先做一些准备工作。测试环境操作系统:CentOS7.2安装依赖这些依赖是我这个环境下的,你可以根据自己的环境安装对应的依赖。yuminstall-ypatchyuminstall-ygdgd-develyuminstall-ylibxslt-develyuminstal......
  • 使用 Nginx 实现域名解析到不同端口的应用
    作为个人网站的服务器,一般都是一台。上面部署了各种应用,都是不同的端口。但是域名只能解析到80端口,而且如果你使用隐形URL转发的话,又需要另外加钱(TX的就是几百块一条....),这就很尴尬了。另一种显性URL又会直接301跳转,体验非常不好。这可如何是好呢?这就需要用到Nginx做反向代理了......
  • express设置跨域
    在app.js的设置中添加//设置允许跨域访问该服务.app.all('*',function(req,res,next){res.header('Access-Control-Allow-Origin','*');res.header('Access-Control-Allow-Headers','Content-Type');res.header(�......
  • 跨域的另一种设置方式
    为了等保一些信息安全之类的问题:需要为系统添加访问白名单,限制哪些IP与端口号可以访问系统,其他的一概不能访问这里涉及到前后端分离,跨域问题可以参考:https://blog.csdn.net/qq_16771097/article/details/117442727需要在CrosConfig类型添加设置配置在配置文件内极少代码改......
  • js:浏览器跨域ajax变通实现 -- flash + js + crossdomain.xml
    使用此方式能很好解决这个问题,因为考虑了php中转形式的双倍时间和莫须有的访问,不是很愿意用,除非不得已,现在找到flash的实现方法,对于能自按的服务器来说这是不错的解决方案,只需要担心的是有人不愿意安装flash控件,且能解决script方式的不能post不足,除非浏览器已经统一支持跨......
  • Nginx安装
    一、Nginx安装1、依赖包yuminstall-ygcc-c++pcrepcre-develzlibzlib-developensslopenssl-develwgetvimtelnetnet-tools2、下载1.22.0版本安装包cd/opt/soft&&wgethttp://nginx.org/download/nginx-1.22.0.tar.gz3、解压tar-zxvfnginx-1.22.0.tar.g......
  • nginx更新静态页面客户端缓存不刷新问题
    问题描述:频繁部署静态资源,nginx自带缓存未刷新通过ftp/sftp上传到nginx的静态页(尤其是打包好的单页应用),有可能遇到客户端缓存不刷新的问题,即使重启nginx都无效客户端浏览器也有缓存,一般关闭进程(手机清理,注意某些app光按返回键退回桌面是不会结束进程的),强制刷新网页等方法可以......
  • Linux&Nginx16_Nginx反向代理6
    一、概念反向代理代理(ReverseProxy)方式是指以代理服务器来接受internet上的连接请求,然后将请求转发给内部网络上的服务器,并将从服务器上得到的结果返回给internet上请求连接的客户端,此时代理服务器对外就表现为一个反向代理服务器。首先我们先理解正向代理,如下图: ......
  • 活字格性能优化技巧(3):如何巧用CDN提升含页面的访问速度
    本文由葡萄城技术团队于博客园原创并首发转载请注明出处:葡萄城官网,葡萄城为开发者提供专业的开发工具、解决方案和服务,赋能开发者。 上两篇中我们分享了如何利用数据库主键和表格设置默认不加载数据来提升应用系统访问的性能。在本篇中一起来看看如何在活字格中利用CDN技术来......