https 请求 http接口 nginx 解决方案

场景:

前后分离环境部署。 前端部署在一台服务器, 对外提供https, 前端代码中请求的接口是http协议。  由于跨协议。导致静态页面正常显示,后台接口被浏览器进行了拦截。获取不到数据。

 

解决方案  通过nginx的反向代理解决。

1, 前端代码中把后台的请求地址 改外 ‘/’, 不要在代码中直接写: http://xxxxxxx.com。

2, 前端代码所在服务器中配置nginx

** http请求转为https** , 目的是地址栏敲 http://a.com  转换给 https://a.com

    server {
        listen       80;
        server_name  xxx.xxxx.com;
        rewrite ^(.*)$   https://$host$1 permanent;
    }

 

** 接受443的https的请求**
    server {
        listen 443;
        server_name xxx.xxxx.com;
        ssl on;
        root   /data/xxx/xxxx/;   // 前端代码地址 
        index index.html index.htm;
        ssl_certificate   ../cert/123.pem;    // SSL 证书, 需申请获取
        ssl_certificate_key  ../cert/123.key; // SSL 证书, 需申请获取
         ssl_session_timeout 5m;
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;
        location /api/ {  //  拦截所有从前端发去的前缀为api的接口请求, 匹配的请求部分代理走http://abcdefg.com
            proxy_pass http://abcdefg.com;
            #proxy_set_header Host $host:$server_port;
            #proxy_set_header X-Real-IP $remote_addr;
            #proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要解决接口跨域问题,可以通过配置Nginx来实现。以下是一种常见的解决方案: 1. 打开Nginx配置文件,通常是位于 `/etc/nginx/nginx.conf` 或 `/etc/nginx/conf.d/default.conf`。 2. 在 `http` 块中添加以下内容: ``` http { ... # 允许跨域请求的域名 add_header Access-Control-Allow-Origin *; # 允许的请求方法 add_header Access-Control-Allow-Methods "GET, POST, OPTIONS, PUT, DELETE"; # 允许的请求头 add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization"; # 允许携带凭证(如Cookie) add_header Access-Control-Allow-Credentials true; ... } ``` 3. 如果需要处理预检请求(OPTIONS),可以添加以下配置: ``` server { ... # 处理预检请求 if ($request_method = 'OPTIONS') { add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods "GET, POST, OPTIONS, PUT, DELETE"; add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization"; add_header Access-Control-Allow-Credentials true; add_header Content-Length 0; add_header Content-Type text/plain; return 204; } ... } ``` 4. 保存配置文件并重新加载Nginx。 这样配置后,Nginx会在响应头中添加相应的CORS(跨域资源共享)相关字段,从而解决接口跨域问题。请注意,此配置将允许所有域进行跨域请求。如需限制只允许特定域名访问,可以将 `Access-Control-Allow-Origin` 的值设置为相应的域名。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值