这篇文章主要介绍“nginx跨域配置教程”,在日常操作中,相信很多人在nginx跨域配置教程问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”nginx跨域配置教程”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
配置nginx跨域
做前端避免不了会遇到跨域的问题,跨域其中一个解决办法就是使用nginx代理来解决,本文也只讨论使用nginx的解决办法。
配置如下,只展示server部分,http部分按照默认配置:
## https server
server {
listen 19443 ssl;
server_name localhost 127.0.0.1;
ssl_certificate local.crt;
ssl_certificate_key local.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
location /scanIdCard/ {
proxy_pass https://127.0.0.1:9199;
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' '*';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
add_header Access-Control-Allow-Headers 'Authorization,X-Requested-With,Content-Type,Origin,Accept' always;
return 200;
}
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
rewrite "^/scanIdCard/(.*)$" /$1 break;
}
}
场景说明:这是一个代理身份证扫描的转发,当前端工程部署到云服务器上时,用户使用浏览器去访问云服务器,那么这时候如果需要在本地电脑上读取身份证信息就会有跨域的问题,为什么呢?因为云服务器上的前端工程的访问地址肯定是域名+端口号,比如:www.baidu.com:19999等等,而身份证读卡器的服务是在本地,访问地址是localhost+一个与19999不同的端口,例如:localhost:8999等等,所以就产生了跨域的问题。不过,跨域是浏览器的限制,并不是服务端的限制,可以通过在服务端设置CORS来解决。
配置项中,https 服务监听端口是19443,所以在前端页面请求中,请求的地址也得是:https://127.0.0.1:19443/scanIdCard/********,这样才能请求到nginx中进行转发。
到此,关于“nginx跨域配置教程”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注天达云网站,小编会继续努力为大家带来更多实用的文章!