Nginx解決跨域
一.靜態頁面服務器
nginx.conf 的配置(其實默認的也是如此,所以作為靜態服務器只需要將靜態文件移動到nginx下的html文件夾裏就可以了)
server {
listen 8094; #監聽端口
server_name localhost; #
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;#文件根目錄
index index.html index.htm;#默認起始頁
}
}
然後打開瀏覽器 輸入 localhost:8094 即可.
二.反向代理服務器-》跨域
下面是未使用Nginx做反向代理的API的url(指定想要訪問的域名:端口號,但是會跨域)。
提示了跨域問題。
利用nginx 通過反向代理 滿足瀏覽器的同源策略實現跨域.
然後我們回到nginx.conf 配置一個反向代理路徑(新增紅色部分)
server { listen 8094; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location / { root html; index index.html index.htm; } location /apis { rewrite ^.+apis/?(.*)$ /$1 break; include uwsgi_params; proxy_pass http://localhost:1894; } }
配置說明:監聽域名為localhost的8094端口號
然後更改一下index1.html的api請求地址。
這樣這個api的地址就跟當前頁面index1.html處於同源位置了。就是我們配置的nginx監聽地址 localhost:8094。
總結:首先這邊的前端頁面發出請求http://localhost:8094/apis/api/basic/get,然後由於Nginx監聽了該域名localhost下的8094端口號,並且配置了反向代理對應的/apis,然後就會由配置的反向代理服務器localhost:1894處理。
來源:https://www.cnblogs.com/bninp/p/5694277.html
Nginx解決跨域