首頁  >  文章  >  運維  >  怎麼使用nginx代理實現靜態資源訪問

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

WBOY
WBOY轉載
2023-05-26 12:25:209195瀏覽

一. 目標:

為了透過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:\Windows\System32\drivers\etc,找到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/;
    }
   }
}

以上是怎麼使用nginx代理實現靜態資源訪問的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除