vue項目通過nginx部署在子目錄


一、前言

最近寫的vue項目,通過nginx部署,並且需要部署在nginx下的子目錄,就是非html根目錄。如果是部署在根目錄,就比較簡單了,但是部署在子目錄,就踩了不少坑。

Linux安裝Nginx詳細教程可以看這篇:https://baijiahao.baidu.com/s?id=1659582871769773387&wfr=spider&for=pc

Nginx配置文件詳解可以看這篇:https://www.cnblogs.com/hunttown/p/5759959.html

千萬使用window版的Nginx去測試,很容易出現錯誤的。

二、配置

我們想要的效果是,比如域名是www.domain.com,我們的項目是配置在www.domain.com/admin 上,

1、vue項目的vue.config.js,publicPath設置為/admin/

module.exports = {
    publicPath: '/admin/',
    assetsDir: 'static',
    productionSourceMap: false,
}

 

2、router/index.js ,base設置為admin

import Vue from 'vue';
import Router from 'vue-router';

Vue.use(Router);

export default new Router({
    mode: "history",
    base: "admin",
    routes: [...]
});

3、配置nginx.conf

 server {
      listen 8080;
      server_name localhost; 
      client_max_body_size 200m;
      location ~ \.(html|css|js|gif|jpg|jpeg|png|ttf|woff|ico|pdf|block|mp3)$ { 
           root html;
           index index.html index.htm; 
      }
      location / {
           root '/usr/local/nginx/html/admin'; 
           index index.html index.htm;
           try_files $uri $uri/ @router;
           add_header Cache-Control no-cache;
           add_header Access-Control-Allow-Origin *;
           add_header Access-Control-Allow-Credentials *;
           add_header Access-Control-Allow-Methods *;
           add_header Access-Control-Allow-Headers *;
      }
      location @router{
           rewrite ^.*$ /admin/index.html last;
      }
      error_page 500 502 503 504 /50x.html; 
      location = /50x.html {
           root html; 
      }
}

 

這里有個重點,我們的路徑是存放在/usr/local/nginx/html/admin,意味着,我們要在html下創建admin文件夾,這個名稱需要跟你想要的域名路徑一致,例如www.domain.com/admin,不然是會請求不到的,將npm run build 生成的dist目錄下的文件copy到admin目錄去,遇到問題,可以看看nginx下logs,解決錯誤很有用的。

 


免責聲明!

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



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