首頁/ 汽車/ 正文

使用nginx部署多個前端專案

基於域名配置

基於埠配置

基於location配置

在正式開始之前,我們先來看一下nginx安裝的預設配置檔案: /etc/nginx/nginx。conf 檔案

使用nginx部署多個前端專案

可以看到圖中的:include /usr/nginx/modules/*。conf,這句話的作用就是可以在nginx啟動載入所有 /usr/nginx/modules/ 目錄下的 *。conf 檔案。 所以,平時我們為了方便管理,可以在此目錄下面定義自己的 xx。conf 檔案即可。

基於域名配置

基於域名配置,前提是先配置好了域名解析。比如說你自己買了一個域名:www。fly。com。 然後你在後臺配置了2個它的二級域名: a。fly。com、 b。fly。com。

配置檔案如下:

配置 a。fly。com 的配置檔案:

vim /usr/nginx/modules/a。conf

server { listen 80; server_name a。fly。com; location / { root /data/web-a/dist; index index。html; }}

配置 b。fly。com 的配置檔案:

vim /usr/nginx/modules/b。conf

server { listen 80; server_name b。fly。com; location / { root /data/web-b/dist; index index。html; }}

這種方式的好處是主機只要開放80埠即可。然後訪問的話直接訪問二級域名就可以訪問。

基於埠配置

配置檔案如下:

配置 a。fly。com 的配置檔案:

vim /usr/nginx/modules/a。conf

server { listen 8000; location / { root /data/web-a/dist; index index。html; }}# nginx 80埠配置 (監聽a二級域名)server { listen 80; server_name a。fly。com; location / { proxy_pass http://localhost:8000; #轉發 }}

配置 b。fly。com 的配置檔案:

vim /usr/nginx/modules/b。conf

server { listen 8001; location / { root /data/web-b/dist; index index。html; }}# nginx 80埠配置 (監聽b二級域名)server { listen 80; server_name b。fly。com; location / { proxy_pass http://localhost:8001; #轉發 }}

可以看到,這種方式一共啟動了4個server,而且配置遠不如第一種簡單,所以不推薦。

基於location配置

配置檔案如下:

配置 a。fly。com 的配置檔案:

vim /usr/nginx/modules/ab。conf

server { listen 80; location / { root /data/web-a/dist; index index。html; } location /web-b { alias /data/web-b/dist; index index。html; }}

注意: 這種方式配置的話,location / 目錄是root,其他的要使用alias。

可以看到,這種方式的好處就是我們只有一個server,而且我們也不需要配置二級域名,並且前端專案裡要配置二級目錄。

nginx location 目錄匹配詳解

nginx location 加不加 / 匹配原則

nginx每個location都是一個匹配目錄,nginx的策略是:訪問請求來時,會對訪問地址進行解析,從上到下逐個匹配,匹配上就執行對應location大括號中的策略,並根據策略對請求作出相應。

server { listen 80; server_name localhost; # http://localhost/wddd01/xxx -> http://localhost:8080/wddd01/xxx location /wddd01/ { proxy_pass http://localhost:8080; } # http://localhost/wddd02/xxx -> http://localhost:8080/xxx location /wddd02/ { proxy_pass http://localhost:8080/; } # http://localhost/wddd03/xxx -> http://localhost:8080/wddd03*/xxx location /wddd03 { proxy_pass http://localhost:8080; } # http://localhost/wddd04/xxx -> http://localhost:8080//xxx,請注意這裡的雙斜線,好好分析一下。 location /wddd04 { proxy_pass http://localhost:8080/; } # http://localhost/wddd05/xxx -> http://localhost:8080/hahaxxx,請注意這裡的haha和xxx之間沒有斜槓,分析一下原因。 location /wddd05/ { proxy_pass http://localhost:8080/haha; } # http://localhost/api6/xxx -> http://localhost:8080/haha/xxx location /wddd06/ { proxy_pass http://localhost:8080/haha/; } # http://localhost/wddd07/xxx -> http://localhost:8080/haha/xxx location /wddd07 { proxy_pass http://localhost:8080/haha; } # http://localhost/wddd08/xxx -> http://localhost:8080/haha//xxx,請注意這裡的雙斜槓。 location /wddd08 { proxy_pass http://localhost:8080/haha/; }}

location目錄後加“/”,只能匹配目錄,不加“/”不僅可以匹配目錄還對目錄進行模糊匹配。而proxy_pass無論加不加“/”,代理跳轉地址都直接拼接。

相關文章

頂部