想要讓不同的url訪問不同的單頁應用, 踩了兩天坑 特記錄如下
目的:
host:port/a 訪問a項目的index.html
host:port/b 訪問b項目的index.html
https://segmentfault.com/a/1190000015428921?tdsourcetag=s_pcqq_aiomsg
用alias可以輕松配置
location ^~/A { alias /XX/A/;//此處為A的路徑 index index.html; try_files $uri $uri/ /A/index.html; } location ^~/B { alias /XX/B/;//此處為B的路徑 index index.html; try_files $uri $uri/ /B/index.html; }
如果用root的話
先上結論
nginx的root配置只有在location / {} 下面才生效 在之后的location里面都不生效
location / { root /var/www/dist; # 這樣的配置是生效的 }
location /a { root /var/www/dist; # 這樣的配置是不生效的 }
所以要么將root配置在location外面, 要么配置在location / 里面
對於用react和vue打包之后的項目, 訪問的都是index.html
因此把單個應用部署到服務器上的話 用的配置參數為
location / { root /var/www/dist; index index.html index.htm; try_files $uri $uri/ /index.html; }
這行代碼的意思是 設定root文件夾為打包好的dist文件夾 如果訪問根節點, 就返回index.html
如果/后面帶有參數, 那么就把參數和root進行拼接之后去找資源
對於這行代碼 如果請求是 /static/js/1.js
那么服務器就會去/var/www/dist/static/js/1.js 找這個文件
如果找不到這個文件, 就會返回try_files的內容. 在這里為/index/html
這個是普通的單頁應用.
那么如果要實現不同的url訪問不同的應用該怎么辦呢
首先.root是不能設置為兩個了. 因為前文已經提過, 要么在server中設置root 要么在location / 中設置. 及全文只能有一個root
那么就用代理的方法來了.
在nginx上啟動兩個本機服務(端口不開啟防火牆的話是訪問不到的
在/etc/nginx/con.d/文件夾下面有一個default.conf, 新建兩個
vim server1.conf
內容
server { listen 9090; location / { root /var/www/dist1; index index.html index.htm; try_files $uri $uri/ /index.html; } }
在創建一個server2.conf
vim server2.conf
server { listen 9091; location / { root /var/www/dist2; index index.html index.htm; try_files $uri $uri/ /index.html; } }
這兩我們就在本機開了兩個服務.分別訪問兩個不同的應用
然后在default里面設置
server { listen 80; server_name localhost; location /a { proxy_pass http://127.0.0.1:9090; } location /b { proxy_pass http://127.0.0.1:9091; } }
這樣雖然可以初步實現了, 但是會發現靜態資源根本訪問不了.
因為靜態資源請求的是/static/ 而這個url到了nginx這里是沒有任何匹配項的. 所以要在配置文件里面做設置
在vue工程里面的 config/index.js里面的build下面有個assetsPublicPath 修改
build: { // Template for index.html index: path.resolve(__dirname, '../dist/index.html'), // Paths assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', assetsPublicPath: '/a/', ...... }
另一個改成/b/
這樣訪問靜態資源的時候 第一個就會訪問/a/static/ 這樣就能找到了.
這樣的首頁已經可以顯示了. 但是如果進行路由跳轉的話 會發現 /a的主頁 跳轉的時候/a就會不見了. 所以在vue-router里面加上
export default new Router({ mode: 'history', base: '/a/', routes: [...] })
這樣每次跳轉的時候都會帶上/a了
至此就可以在同一個服務器上通過nginx實現不同的url訪問不同的應用了 並且互不干擾.