怎么使用nginx代理實現靜態資源訪問

一. 目標:

為了通過nginx請求靜態資源(css、圖片等),通過nginx代理進行頁面預覽。

二. 實現效果:

通過瀏覽器輸入nginx代理地址以打開頁面方式訪問本地html文件,也可以通過訪問代理路由訪問接口實現頁面預覽功能.
注:我演示的是在本地windows開發環境下的配置

三. 具體配置

1. nginx配置本地靜態工程代理

找到nginx配置文件nginx.conf,配置nginx代理

server{ listen???????80;  #前端門戶工程 location?/?{ ????alias???D:/workspace/sc-multipl-static-web-project/; ????index??index.html; }

說明:
D:/workspace/sc-multipl-static-web-project/ 是你的前端工程文件路徑

保存配置文件并重啟nginx,瀏覽器輸入 localhost:80 驗證

2. win10配置本地域名實現域名訪問

域名訪問實際上是通過對應ip地址,再通過ip訪問服務的,如果我們沒有開通互聯網域名,可以通過配置本地域名映射模擬域名訪問的(只在本機有效)
打開C:WindowsSystem32driversetc,找到hosts文件,如果沒有則自己新增一個,以管理員身份打開編輯,輸入

127.0.0.1 www.chen123.com

再打開nginx配置文件

server{ ????listen???????80; ????server_name??www.chen123.com; ????ssi?on; ????ssi_silent_errors?on; ????#前端門戶工程 ????location?/?{ ????????alias???D:/workspace/sc-multipl-static-web-project/; ????????index??index.html; ????} ???? ???}

保存配置文件并重啟nginx,瀏覽器輸入 localhost:chen123 驗證

3.nginx配置頁面預覽路由

首先,你要先實現一個頁面預覽接口,返回格式為String類型,內容其實就是html的文本內容
再打開nginx配置文件

http?{ ????include???????mime.types; ????default_type??application/octet-stream;  ????sendfile????????on; ????#tcp_nopush?????on;  ????#keepalive_timeout??0; ????keepalive_timeout??65;  ????#gzip??on; ????#cms頁面預覽路由 ????upstream?cms_server_pool?{ ????????server?127.0.0.1:31001?weight=10; ????}  ????server{ ????listen???????80; ????server_name??www.xuecheng.com; ????ssi?on; ????ssi_silent_errors?on; ????#前端門戶工程 ????location?/?{ ????????alias???D:/workspace/sc-multipl-static-web-project/; ????????index??index.html; ????} ????#頁面預覽 ????location?/cms/preview/?{ ????????proxy_pass?http://cms_server_pool/cms/preview/; ????} ???? ???} }

http://cms_server_pool/cms/preview/ 就是你要實現的頁面預覽接口,通過配置路由實現跳轉到真實地址,

????upstream?cms_server_pool?{ ????????server?127.0.0.1:31001?weight=10; ????????#如果有多個服務器,可以寫在下面,例如 ????????#server?127.0.0.1:31002?weight=10; ????}

保存配置文件并重啟nginx,瀏覽器輸入 http://cms_server_pool/cms/preview 驗證

我本地的nginx配置如下

events?{ ????worker_connections??1024; }  http?{ ????include???????mime.types; ????default_type??application/octet-stream;  ????sendfile????????on; ????keepalive_timeout??65;  ????#gzip??on; ????#cms頁面預覽路由 ????upstream?cms_server_pool?{ ????????server?127.0.0.1:31001?weight=10; ????}  ????server{ ????listen???????80; ????server_name??www.xuecheng.com; ????ssi?on; ????ssi_silent_errors?on; ????#前端門戶工程 ????location?/?{ ????????alias???D:/workspace/sc-multipl-static-web-project/; ????????index??index.html; ????} ????#頁面預覽 ????location?/cms/preview/?{ ????????proxy_pass?http://cms_server_pool/cms/preview/; ????} ???} }

? 版權聲明
THE END
喜歡就支持一下吧
點贊12 分享