利用nginx反向代理解决前端跨域问题的方案

chat

前端遇到跨域问题一般会本地搭建代理服务转发,比如使用webpack代理,还有就是jsonp、使用浏览器插件、让后端加允许跨域的响应头 等方式解决。

我在使用nginx反向代理功能时想到利用nginx反向代理后端的api接口也可以解决跨域问题。这样做的好处是不需要前端或后端在工程项目中做任何代码修改,在本机或者一台服务器搭建nginx服务即可,在一台服务器上开启反向代理后,所有开发人员都可以通过这个反向代理服务进行开发调试。

我用的代理服务 nginx 配置文件:

location /
{
    expires 12h;
    if ($request_uri ~* "(php|jsp|cgi|asp|aspx)")
    {
         expires 0;
    }
    proxy_pass http://120.205.22.66:9093;
    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 REMOTE-HOST $remote_addr;
    add_header Access-Control-Allow-origin '*';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,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_connect_timeout 30s;
    #proxy_read_timeout 86400s;
    #proxy_send_timeout 30s;
    #proxy_http_version 1.1;
    #proxy_set_header Upgrade $http_upgrade;
    #proxy_set_header Connection "upgrade";

    add_header X-Cache $upstream_cache_status;

    #Set Nginx Cache

        add_header Cache-Control no-cache;
}

需要注意的是:
proxy_set_header 是用来重定义发往代理服务器服务器的请求头。
add_header 是用于设置response header

允许跨域的配置就是这些:

add_header Access-Control-Allow-origin '*';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,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;
    }

版权声明:
作者:东明兄
链接:https://blog.crazyming.com/note/1792/
来源:CrazyMing
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
海报
利用nginx反向代理解决前端跨域问题的方案
nginx反向代理api接口 解决前端跨域问题
<<上一篇
下一篇>>
chat