server { listen 80; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main;
root "D:/webserver/phpstudy/WWW";
#注釋的代碼開始
#location / {
# index index.html index.htm index.php l.php;
# autoindex off;
#}
#注釋的代碼結束
# 添加的代碼開始 location / { proxy_pass http://localhost:8080; # 本地啟動的項目服務器 proxy_redirect default; } location ^~ /apis { rewrite ^/apis/(.*)$/$1 break; proxy_pass http://www.xxx.com/; # 后台api接口地址 }
# 添加的代碼結束
#error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root "D:/webserver/phpstudy/WWW"; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { # proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # location ~ \.php(.*)$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_split_path_info ^((?U).+\.php)(/?.+)$; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info; include fastcgi_params; } # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { # deny all; #} }
1、修改完成Nginx配置文件之后需要重啟服務
2、如果代理配置正確,此時在瀏覽器中輸入 localhost 打開 其中展示的內容應該是 localhost:8080 下的頁面內容
在瀏覽器中輸入 localhost/apis/report/data.json 展示的內容應該是 www.xxx.com/report/data.json 下的json數據。
如果打開這兩個頁面不是的話,那么就可能是配置錯誤了
2、我使用的是phpstudy 所以Nginx配置文件是在 其他選項菜單 -> 打開配置文件 -> nginx-conf
3、開始使用反向代理
(1) 本地項目的地址是 localhost:8080 在此項目文件下給 www.xxx.com/report/data.json 發送一個get請求
axios.get('/apis/report/data.json').then((res) => {
console.log(res)
}).catch((err) => {
console.log(err)
})
(2) 此時我們如果直接打開 localhost:8080 頁面去看,會發現請求失敗 會報一個404 的錯誤代碼
(3) 一開始我也沒明白,后面才想到,
因為 localhost 的頁面內容是localhost:8080的 ,
我就打開了localhost頁面 發現請求成功數據接收到了
