使用nginx部署多個前端項目


使用nginx部署多個前端項目

個人總結了3種方法來實現在一台服務器上使用nginx部署多個前端項目的方法。

  • 基於域名配置
  • 基於端口配置
  • 基於location配置

在正式開始之前,我們先來看一下nginx安裝的默認配置文件: /etc/nginx/nginx.conf 文件

可以看到圖中的:include /usr/nginx/modules/*.conf,這句話的作用就是可以在nginx啟動加載所有 /usr/nginx/modules/ 目錄下的 *.conf 文件。 所以,平時我們為了方便管理,可以在此目錄下面定義自己的 xx.conf 文件即可。但是注意,一定要以.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,而且我們也不需要配置二級域名。並且前端項目里要配置二級目錄

react 配置請參考: https://blog.csdn.net/mollerlala/article/details/96427751?depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-2&utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-2

vue 配置請參考:https://blog.csdn.net/weixin_33868027/article/details/92139392

返回頂部↑


免責聲明!

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



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