Nginx配置Web項目(多頁面應用,單頁面應用)


目前前端項目 可分兩種: 多頁面應用,單頁面應用。

單頁面應用 入口是一個html文件,頁面路由由js控制,動態往html頁面插入DOM。

多頁面應用 是由多個html文件組成,瀏覽器訪問的是對應服務器的html文件。

多頁面應用

目錄結構

.
├── README.md
├── html
    ├── index.html
    └── project.html
└── img
    └── bg.jpg

上面這種情況 index.html 不在根目錄下,nginx.conf 需要配置更加准確。

nginx配置

先來看一個有問題的nginx配置,因為做了太多的資源適配,會導致頁面內資源訪問或頁面跳轉有問題。

有問題的nginx配置

server {
  listen 443 ssl;
  server_name www.whosmeya.com;
  ssl on;
  ssl_certificate 1_www.whosmeya.com_bundle.crt;
  ssl_certificate_key 2_www.whosmeya.com.key;

  location / {
    root /root/libs/landing-page/;
    try_files $uri $uri/index.html $uri.html @fallback;
  }

  location @fallback {
    root /root/libs/landing-page/;
    rewrite .* /html/index.html break;
  }
}

問題解析:
如果路徑正確,沒問題。
如果路徑錯誤,會將資源定位到/html/index.html,且路徑不跳轉。
問題是如果/html/index.html用了相對路徑獲取資源或跳轉,就會獲取不到或跳轉不過去。

例如:
訪問 https://www.whosmeya.com/a/b 也能定位到資源 /html/index.html
頁面內有個a鏈接 href="./project.html", 願意是跳轉/html/project.html,但在https://www.whosmeya.com/a/b下,會被跳轉到https://www.whosmeya.com/a/project.html,然后沒有對應資源,也會被定位到 /html/index.html

調整后的nginx配置

針對上面問題,需要針對多頁面應用對nginx配置做修改:

server {
  listen 443 ssl;
  server_name www.whosmeya.com;
  ssl on;
  ssl_certificate 1_www.whosmeya.com_bundle.crt;
  ssl_certificate_key 2_www.whosmeya.com.key;

  location / {
    root /root/libs/landing-page/;
    try_files $uri $uri.html @fallback;
  }

  location @fallback {
    root /root/libs/landing-page/;
    rewrite .* /html/index.html redirect;
  }
}

改動點

try_files $uri $uri/index.html $uri.html @fallback; -> try_files $uri $uri.html @fallback;
rewrite .* /html/index.html break; -> rewrite .* /html/index.html redirect;

這樣會 直接找 $uri 或者 $uri.html, 找不到會重定向到 首頁/html/index.html

補充:
rewrite最后一項參數

參數 說明
last 本條規則匹配完成后繼續向下匹配新的location URI規則
break 本條規則匹配完成后終止,不在匹配任何規則
redirect 返回302臨時重定向
permanent 返回301永久重定向

單頁面應用

目錄結構

.
├── asset-manifest.json
├── favicon.ico
├── index.html
├── manifest.json
├── precache-manifest.e641bb60bd40b24c7a13e1d60c2a5baa.js
├── service-worker.js
└── static
    ├── css
    │   ├── main.2cce8147.chunk.css
    │   └── main.2cce8147.chunk.css.map
    ├── js
    │   ├── 2.b41502e9.chunk.js
    │   ├── 2.b41502e9.chunk.js.map
    │   ├── main.05bebd98.chunk.js
    │   ├── main.05bebd98.chunk.js.map
    │   ├── runtime~main.a8a9905a.js
    │   └── runtime~main.a8a9905a.js.map
    └── media
        └── logo.5d5d9eef.svg

nginx配置

server {
  listen 80;
  server_name react.whosmeya.com;

  location / {
    root /root/libs/whosmeya-react/;
    try_files $uri @fallback;
  }

  location @fallback {
    root /root/libs/whosmeya-react/;
    rewrite .* /index.html break;
  }
}

單頁面應用 配置思路是:
服務器收到的所有訪問,能訪問到就返回資源,訪問不到就返回index.html。
fallback必須要設置,不然刷新頁面會404。
rewrite要使用break,不需要redirect路由重定向,因為訪問資源都是基於根目錄 / 。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM