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

巧用Nginx配置解决跨域问题的更多相关文章

  1. 使用Nginx来解决跨域的问题

    使用Nginx来解决跨域的问题 nginx的版本:(查看nginx命令: /usr/local/nginx/sbin/nginx -v) nginx/1.4.3 问题是:前端项目域名是 a.xxxx. ...

  2. 【Nginx】使用Nginx如何解决跨域问题?看完这篇原来很简单!!

    写在前面 当今互联网行业,大部分Web项目基本都是采用的前后端分离模式.前端为H5项目,后端为Java.PHP.Python等项目.而且大部分后端服务并不会只部署一套服务,而是会采用Nginx对后端服 ...

  3. 一篇文章让你搞懂如何通过Nginx来解决跨域问题

    Nginx跨域实现   首先大家要搞清楚什么是跨域,为什么会有跨域情况的出现.哪些情况属于跨域? 跨域:由于浏览器的同源策略,即属于不同域的页面之间不能相互访问各自的页面内容 注:同源策略,单说来就是 ...

  4. vue webpack配置解决跨域问题

    现在基本项目都是实行前后端分离的原则,不管是ng 或者是vue 在开发中都无法避免跨域的这个问题 本人刚上手第一个vue项目,在调用api的时候出现了跨域的这个问题 这是封装好一个简单的post 请求 ...

  5. vue项目开发,用webpack配置解决跨域问题

    今天在本地开发时候碰到了跨域的问题,突然觉着跨域问题在所难免啊,之前没有没有碰到总觉着解决跨域很高大上的样纸,其实就是受限于网络的同源策略,跨域前后端都可以进行处理. 1,后端更改header hea ...

  6. nginx 配置ajax跨域访问php接口

    在nginx.conf里面,找到server项,并在里面添加如下配置 location ~ \.php?($|/) { #try_files $uri =; #handel cosr by mao a ...

  7. 服务端 Cros 配置解决跨域

    <system.webServer> <httpProtocol> <customHeaders> <remove name="Access-Con ...

  8. Nginx配置解决NetCore的跨域

    使用Nginx配置解决NetCore的跨域 废话不多说,直接上Nginx配置 server { listen 80; server_name 你的Id或域名; location / { add_hea ...

  9. 【手摸手,带你搭建前后端分离商城系统】02 VUE-CLI 脚手架生成基本项目,axios配置请求、解决跨域问题

    [手摸手,带你搭建前后端分离商城系统]02 VUE-CLI 脚手架生成基本项目,axios配置请求.解决跨域问题. 回顾一下上一节我们学习到的内容.已经将一个 usm_admin 后台用户 表的基本增 ...

  10. Vue使用Axios实现http请求以及解决跨域问题

    Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中.Axios的中文文档以及github地址如下: 中文:https://www.kancloud.cn/y ...

随机推荐

  1. python 编程找出矩阵中的幸运数字:说明,在一个给定的M*N的矩阵(矩阵中的取值0-1024,且各不相同),如果某一个元素的值在同一行中最小,并且在同一列中元素最大,那么该数字为幸运数字。

    假设给定矩阵如下: matrix=[[10,36,52], [33,24,88], [66,76,99]] 那么输出结果应为66(同时满足条件) 代码如下: arr=[[10,36,52], [33, ...

  2. django orm性能优化

    参考: django 分页查询大表,很慢 面试小知识:MySQL索引相关 MySQL 用 limit 为什么会影响性能? 前言 orm性能优化是一件很重要的事,一般万条以上的数据都需要优化处理了. 这 ...

  3. CentOS7 进入修复模式的办法

    有时候配置Centos文件修改错误会导致系统无法登录,可以通过修复模式进行单用户运行模式,进行修复. 具体操作如下: 1.重启服务器,在选择内核界面使用上下箭头移动 2.选择内核并按"e&q ...

  4. Delaunay triangulation 的实现

    在GitHub 找到的别人的代码:https://github.com/earthwjl/DelaunayTriangulate 解压后是这样的:(没有x64) 直接就有了.sln工程文件,于是用Vi ...

  5. LeedCode 85. 最大矩形(/)

    原题解 题目 约束 题解 解法一 class Solution { public: int maximalRectangle(vector<vector<char>>& ...

  6. Hive启动留下的RunJar进程不能使用Kill -9 杀不掉怎么办?

    1.问题示例 [Hadoop@master Logs]$ jps 3728 ResourceManager 6976 RunJar 7587 Jps 4277 Master 3095 NameNode ...

  7. spring事件发布与监听

    一.组成部分 spring的事件监听有三个部分组成,事件(ApplicationEvent).监听器(ApplicationListener)和事件发布操作. 二.具体实现 事件 事件对象就是一个简单 ...

  8. Unity泛型单例模式

    using System.Collections; using System.Collections.Generic; using UnityEngine; public class Singleto ...

  9. Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.1:test (default-test) on

    解决错误 Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.1:test (default-test ...

  10. Python项目案例开发从入门到实战-1.4Python图形界面设计

    Python提供了多个图形开发界面的库,常用的Python GUI库如下. -Tkinter:Python内置模块 -wxPython -Jython 1.4.1创建Windows窗口 import ...