Nginx配置同域名下多個Vue項目
開始搗鼓nginx配置,我採用的是分文件的方式搗鼓的:
首先nginx.conf文件中include所有的配置進來:
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
gzip on;
gzip_disable "msie6";
include /etc/nginx/conf.d/*.conf; #這一句將conf.d目錄下的所有conf配置文件引入
}
然後在conf.d目錄下創建每個項目對應的nginx配置文件
1、通過多端口實現
這個其實很簡單,通個域名不同端口進入不同項目,只需要nginx監聽對應的端口然後指定對應的目錄就好,代碼如下
對於項目一我們希望通過默認域名進入,即綁定80端口:
####項目一nginx配置文件
server {
#訪問端口(頁面訪問端口)
listen 80;
server_name xxx;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
location / {
# 前端工程根目錄
root /x/x/x/x/dist;
index index.html;
}
location /** {
# 前端工程根目錄
root /x/x/x/x/dist;
index index.html;
}
#沒有跨域需求可以不配
#代理路徑 地址是以spi開頭的 ‘/api開頭的都走這個代理’
# 將前端訪問的後臺端口變更爲‘前臺id:前臺端口/api/xxx/xxx’
location /api {
#正則表達式匹配路徑
rewrite ^/api/(.*)$ /$1 break;
include uwsgi_params;
#後端端口(後端最終訪問的端口)
proxy_pass http://x.x.x.x:8081 ;
}
location @router {
rewrite ^.*$ /index.html last;
}
}
項目二,希望通過8081進入,即域名.com:8081這樣的方式訪問,代碼如下:
server {
#訪問端口(頁面訪問端口)
listen 8081;
server_name localhost;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
location / {
# 前端工程根目錄
root /x/x/x/x/dist;
index index.html;
}
location /** {
# 前端工程根目錄
root /x/x/x/x/dist;
index index.html;
}
#沒有跨域需求可以不配
#代理路徑 地址是以spi開頭的 ‘/api開頭的都走這個代理’
# 將前端訪問的後臺端口變更爲‘前臺id:前臺端口/api/xxx/xxx’
location /api {
#正則表達式匹配路徑
rewrite ^/api/(.*)$ /$1 break;
include uwsgi_params;
#後端端口(後端最終訪問的端口)
proxy_pass http://x.x.x.x:8081 ;
}
location @router {
rewrite ^.*$ /index.html last;
}
}
二、同端口同域名不同目錄方式訪問不同項目
因爲公衆號的授權回調是驗證域名的,端口號不起作用,所以現在一個校園商城有三個vue項目,分別是:公衆號前臺、後臺管理系統網頁端、配送員配送系統。
首先對於一個域名默認路徑訪問的是公衆號前臺項目,通過二級目錄定位到配送系統,我們如下配置,:
server {
#訪問端口(頁面訪問端口)
listen 80;
server_name senfancollege.com;
#root /usr/local/www/;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
##項目一,同過域名直接訪問
location / {
#前端工程根目錄
alias /x/x/x/x/dist/;
index index.html;
}
##項目二,同過域名.com/YYY訪問
location /YYY {
# 前端工程根目錄
alias /x/x/x/x/dist/;
try_files $uri $uri/ @router;
index index.html;
}
# 沒有跨域需求可以不配
#代理路徑 地址是以spi開頭的 ‘/api開頭的都走這個代理’
# 將前端訪問的後臺端口變更爲‘前臺id:前臺端口/api/xxx/xxx’
location /api {
#正則表達式匹配路徑
rewrite ^/api/(.*)$ /$1 break;
include uwsgi_params;
#後端端口(後端最終訪問的端口)
proxy_pass http://x.x.x.x:8081 ;
}
location @router {
rewrite ^.*$ /index.html last;
}
}
這裏我沒有分配置文件,感興趣的同學可以試試
附上nignx重新加載配置文件命令
service nginx reload