Nginx轉發指定請求,解決請求跨域問題

當初被這個跨域問題搞得頭都大了(那個時候還太菜了)前端


通常前端的請求是 網址都是 域名(端口 訪問的是80 或者 443)
然後端的服務是 8080 端口,這個時候你請求 http://106.520.156.210:8080/vic-indoor-pc/selectAllUser
就會報跨域問題了(端口不一樣)後端

因此我在每一個請求加了統一的前綴 /api ,請求變成了 http://106.520.156.210/api/vic-indoor-pc/selectAllUse (端口必須和前端同樣)api

前端發送請求: http://106.520.156.210/api/vic-indoor-pc/selectAllUse
Nginx轉發變成了: http://106.520.156.210:8080/vic-indoor-pc/selectAllUse跨域

通過Nginx 這樣轉發,對於瀏覽器來講,訪問的就是 80 ,可是請求的實際上是 8080
rewrite "^/api/(.*)$" /$1 break; 這句就是把 /api 給刪除掉了而後 轉發到了 http://106.520.156.210:8080/瀏覽器

location /api/vic-indoor-pc {

                        proxy_set_header Client-IP      $Remote_addr;
                        proxy_pass http://106.520.156.210:8080/;
                        rewrite "^/api/(.*)$" /$1 break; 

                }

複製代碼

我還碰到了 下載 阿里OSS 存儲跨域的問題,也是這麼解決的。(加上統一前綴)bash

location /img/report {

                        proxy_set_header Client-IP      $Remote_addr;
                        proxy_pass https://bilibili.oss-cn-shenzhen.aliyuncs.com/;
                        rewrite "^/img/(.*)$" /$1 break;
                }
複製代碼
相關文章
相關標籤/搜索