

巧用Nginx配置解决跨域问题 - 我俩绝配
source link: https://www.cnblogs.com/lihaoyang/p/17303937.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

页面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
Recommend
-
19
zuul+security跨域Cors问题解决 简介 场景 在服务后台都会出现跨域cors问题,不过一般spring解决起来比较方便,在框架+框架的基础上,问题就显得特别明显了,各种冲突,不了解源码的运行原理,解决起来...
-
40
源码 package main import ( "github.com/gin-gonic/gin" "strings" "fmt" "net/http" ) func main() { r := gin.Default() r.Use(Cors()) //开启中间件 允许使用跨域请求 r.run() }...
-
48
Nuxt 是 Vue 项目服务器端渲染(SSR)解决方案。而在使用时,就会遇到前后端分离情况下的域名或端口不一致导致的跨域问题。本文将介绍如何通过设置代理解决 Nuxt 与
-
49
<h1> Go | Gin 解决跨域问题跨域配置 </h1> 前言 在前后端分离的项目中,经常会遇到跨域问题,遇到问题该如何解决呢?! 一、关于跨域解决方案 关于跨域的解决方法,大部分可以分为...
-
9
Django 通过设置 CORS 解决跨域问题 一、Ajax 跨域请求Ajax 请求一个目标地址为非本域(协议、主机、端口任意一个不同)的 web 资源。 前端http://192.168.10.50:8080 后端
-
41
后端域名为A.abc.com,前端域名为B.abc.com。浏览器在访问时,会出现跨域访问。浏览器对于javascript的同源策略的限制。 HTTP请求时,请求本身会返回200,但是返回结果不会走success,并且会在浏览器console中提示: 已拦截跨源请求:同源策略禁...
-
8
前后端分离项目跨域问题是不可避免的。通常情况下前端由React、Vue等框架编写,通过ajax请求服务端API,传输数据用json格式。 那么为什么...
-
10
软装绝配,巧用花瓶让你家大放异彩! 花瓶 时间:2021-11-17 07:00 | 阅读: 209
-
6
妈妈以前收走我所有的压岁钱,我俩约定成年后归还我。现在我二十多岁了,她还是不还我,怎么办? - 知乎妈妈以前收走我所有的压岁钱,我俩约定成年后归还我。现在我二十多岁了,她还是不还我,怎么办?
-
5
V2EX › Apple 我是 iPhone12, 我媳妇是 iPhone11, 我俩想换机用. 如何交换里面的数据?
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK