巧用Nginx配置解决跨域问题

这篇具有很好参考价值的文章主要介绍了巧用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配置解决跨域问题

 文章来源地址https://www.toymoban.com/news/detail-410307.html

 

这样配置的话,前端页面在域名下: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配置解决跨域问题的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • nginx处理cros跨域遇到的各种问题及解决方案,以及https配置和浏览器https不安全问题处理

    提示:本人在生产部署服务时遇到一系列跨域问题和https配置问题,特此做以下记录: 跨域是指a页面想获取b页面资源,如果a、b页面的协议、域名、端口、子域名不同,或是a页面为ip地址,b页面为域名地址,所进行的访问行动都是跨域的,而浏览器为了安全问题一般都限制了

    2024年02月02日
    浏览(40)
  • 记:vite3+vue3+axios前端项目跨域问题解决【前端和服务器nginx配置】

    前言:什么是跨域,网上一搜一大把,所以这里直接跳过,直入主题。 处理方式:不通过后端处理跨域,通过前端+服务器nginx处理。 1.前端涉及处理跨域的必要配置(开发环境、生产环境):vite3、vue3、axios 2.服务器涉及处理跨域的配置(生产环境):nginx【主要用到其配置

    2024年02月01日
    浏览(40)
  • Nginx解决跨域问题

    目录 前言 一、跨域问题 1.什么是跨域  2.CORS 二、Nginx跨域处理 三.补充 这几天出现了一个问题,我们中的一个A系统需要给B系统调用,造成了跨域问题。 1.什么是跨域 当一个请求url的协议、域名、端口三者之间任意一个与当前页面url不同即为跨域。  2.CORS CORS是一个W3C标准,

    2024年02月16日
    浏览(45)
  • Nginx跨域问题的解决方法

    Web前端开发经常会遇到跨域访问,如果没有办法让后台开放访问域,调用接口就会被浏览器拦截。解决跨域问题的方案,可以搭建一个后台服务做中间转发,也可以用 nginx https://so.csdn.net/so/search?q=nginx 转发。 问题发生在nginx 反向代理 https://so.csdn.net/so/search?q=%E5%8F%8D%E5%90%91%E

    2024年02月11日
    浏览(34)
  • 使用Nginx解决跨域问题

    目录 使用Nginx解决跨域问题 1、修改浏览器、客户端访问地址 2、在nginx.conf配置文件需配置server 3、在Nginx中配置客户端访问的接口(按照规则或通配),并设置被代理的服务器 4、在Nginx中统一配置客户端访问的头部信息(解决跨域问题) 5、在服务器端设置相应的头部信息(

    2024年02月13日
    浏览(47)
  • 使用nginx解决跨域问题(前端解决)

    情况是这样的:编写好的前端页面本地打开是没有问题的,请求都能发出去,接收到正确的响应结果。但是,使用nginx来部署这个页面就会出现跨域问题。 跨域 :由于浏览器的同源策略,即属于不同域的页面之间不能相互访问各自的页面内容 注 :同源策略,单说来就是同协

    2024年02月11日
    浏览(34)
  • Nginx 代理解决跨域问题分析

    当你遇到跨域问题,不要立刻就选择复制去尝试。请详细看完这篇文章再处理 。我相信它能帮到你。 分析前准备: 前端网站地址:http://localhost:8080 服务端网址:http://localhost:59200  首先保证服务端是没有处理跨域的,其次,先用postman测试服务端接口是正常的。 当网站8080去

    2024年02月09日
    浏览(44)
  • nginx如何解决前后端跨域问题

    Nginx 可以通过以下两种方式来解决前后端跨域问题: 添加 CORS 头部 Nginx 可以通过添加 CORS 头部来解决跨域问题。CORS(Cross-Origin Resource Sharing)是一种机制,它允许 Web 应用程序从不同的域访问其资源。要在 Nginx 中添加 CORS 头部,可以在 Nginx 配置文件中的特定位置添加以下代

    2024年02月05日
    浏览(33)
  • 解决你的 Nginx 代理跨域问题详细完整版

    当你遇到跨域问题,不要立刻就选择复制去尝试。请详细看完这篇文章再处理 。我相信它能帮到你。 分析前准备: 前端网站地址:http://localhost:8080 服务端网址:http://localhost:59200  首先保证服务端是没有处理跨域的,其次,先用postman测试服务端接口是正常的 当网站8080去访

    2024年02月21日
    浏览(44)
  • 开发环境中解决跨域问题,nginx和tomcat

    有两种方式,一种是在前端配置,一种是在后端配置 需要在前后端都配置 在前端新建axios的时候添加withCredentials: true 在后端添加

    2024年02月08日
    浏览(29)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包