初次配置Nginx反向代理,解決跨域時遇到了問題
問題描述
我想通過 nginx 的反向代理功能,解決跨域請求的問題
PM25 有一個開放接口,只要使用 GET 請求對應的 URL 就能返回對應的 JSON 數據
我想通過自己的 nginx 做代理,訪問 主域名下特定的 字段 ,從而獲取 PM25 的 JSON 數據
nginx.conflocation /get_aqi_details_hangzhou { proxy_pass http://www.pm25.in/api/querys/pm2_5.json?city=hangzhou&token=5j1znBVAsnSf5xQyNQyq; proxy_set_header Host $host;}
我想通過訪問 主域名/get_aqi_details_hangzhou 去獲取這個數據,每次配置完之后也重啟 nginx
在實際操作時,始終無法成功,報 404
是什么原因導致的呢?
問題解答
回答1:沒見過這么用 proxy_pass 的。proxy_pass 的意思是,nginx 作為代理,把請求傳遞給指定的主機。所以你需要把請求路徑 rewrite 成它需要的那樣。
location /get_aqi_details_hangzhou {rewrite .* /api/querys/pm2_5.json?city=hangzhou&token=5j1znBVAsnSf5xQyNQyq break; proxy_pass http://www.pm25.in; }
