一招解決Vue多頁面路由history模式【開發到部署】

開啓多頁面模式

module.exports = {
   pages: {},
}

官方文檔-多頁面配置html

路由模式

const mainRoutes = [
    {
        path: "/",
        name: "main",
        component: Layout,
        redirect: "/home",
        children: [
            {
                path: "/home",
                name: "home",
                component: () => import("@/html/sysadmin/views/home/home"),
                meta: {
                    title: "home",
                },
            },
        ],
    },
];

const router = new Router({
    mode: "history", // 配置history模式
    base: "/sysadmin", // 取個應用路徑名字
    routes: mainRoutes,
});

官方文檔-vue-Router basevue

開發模式

vue.config.js

添加如下配置nginx

publicPath:'/', // 注意publicPath的路徑是斜槓
configureWebpack: {
        devServer: {
            historyApiFallback: {
                verbose: true,
                rewrites: [
                    { from: /^\/index\/.*$/, to: "/index.html" }, 
                    { from: /^\/sysadmin\/.*$/, to: "/sysadmin.html" }
                ],
            },
        },
    },

image.png

線上nginx模式

打包目錄

image.png

配置nginx

server {
        listen       9041;
        server_name  pb5;
        client_max_body_size 500m;

        location / {
            root   /usr/local/dist;
            index  index.html index.htm;
        }
        
        location ^~ /api { # api接口代理
            rewrite  ^/api/(.*)$ /$1 break;
            proxy_set_header Host $host:9041;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header REMOTE-HOST $remote_addr;
            proxy_pass http://192.168.10.38:8080; # 內網IP
            
        }
        
        # 注意nginx的執行順序是先匹配的 /sysadmin的 ,而後再匹配 /
        
        location /sysadmin { # 這裏的配置就是至關於配置了個路徑,而後nginx作了一層攔截
             root   /usr/local/dist;
             index sysadmin.html;
             try_files $uri $uri/ /sysadmin.html;
        }
    }

若是你的項目是二級目錄,須要這樣配置,對比看下不一樣店

location / { # 根目錄
            root   /usr/local/dist;
            index  index.html index.htm;
        }
location  ^~/sysadmin{
        roxy_redirect  off; # 若是是域名須要打開,ip不須要
        alias   /usr/local/dist/sysadmin; # 二級目錄 
        index  index.html index.htm;    
        try_files $uri $uri/ /sysadmin/index.html;            
}

image.png

解釋

關於alias能夠這篇文章api

$uri 這個是nginx的一個變量,存放着用戶訪問的地址,好比:http://xxx.com/sysadmin/sysadmin.html,$uri就是sysadmin.html網站

$uri/ 表明訪問的是一個目錄,好比:http://xxx.com/sysadmin/requirelist/ ,那麼 $uri/ 就是 /sysadmin/requirelist/ui

nginx中try_files的含義:try_files 會去嘗試到網站目錄讀取用戶訪問的文件,若是第一個變量存在,就直接返回;不存在繼續讀取第二個變量,若是存在,直接返回;不存在直接跳轉到第三個參數上。spa

相關文章
相關標籤/搜索