鍍金池/ 問答/Linux  HTML/ vue部署后,訪問路徑問題

vue部署后,訪問路徑問題

問題:

訪問 https://zkaim.com/ocms/ 正常
訪問 https://zkaim.com/ocms 就報404

已知vue2.5.9:

nginx配置如下

location /ocms/ {
            root /home;
            #index  index.html index.htm;
        }

vue路由配置如下

mode: 'history',
base: '/ocms/'
...

以及config配置中的assetsPublicPath跟base相同

回答
編輯回答
執(zhí)念

base: '/ocms'試試?

2018年2月2日 12:34
編輯回答
貓小柒

今天剛回答了一個類似的問題,我就直接把答案粘貼過來了!
單頁面應(yīng)用應(yīng)該放到nginx或者apache、tomcat等web代理服務(wù)器中,同時要根據(jù)自己服務(wù)器的項目路徑更改vue的路由地址。
如果說項目是直接跟在域名后面的,比如:http://www.sosout.com ,根路由就是 '/'。
如果說項目是直接跟在域名后面的一個子目錄中的,比如:http://www.sosout.com/children ,根路由就是 '/children ',不能直接訪問index.html。

以配置Nginx為例,配置過程大致如下:
(假設(shè):1、項目文件目錄: /mnt/html/vueCli(vueCli目錄下的文件就是執(zhí)行了打包后生成的目標(biāo)目錄下的文件);2、訪問域名:vue.sosout.com)

進(jìn)入nginx.conf新增如下配置:

server {
    listen 80;
    server_name vue.sosout.com;
    root /mnt/html/vueCli;
    index index.html;
    location ~ ^/favicon.ico$ {
        root /mnt/html/vueCli;
    }

    location / {
        try_files $uri $uri/ /index.html;
        proxy_set_header   Host             $host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto  $scheme;
    }
    access_log  /mnt/logs/nginx/access.log  main;
}

注意事項:
1、配置域名的話,需要80端口,成功后,只要訪問域名即可訪問的項目
2、如果你使用了vue-router的history模式,在nginx配置還需要重寫路由:

server {
    listen 80;
    server_name vue.sosout.com;
    root /mnt/html/vueCli;
    index index.html;
    location ~ ^/favicon.ico$ {
        root /mnt/html/vueCli;
    }
    
    location / {
        try_files $uri $uri/ @fallback;
        index index.html;
        proxy_set_header   Host             $host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto  $scheme;
    }
    location @fallback {
        rewrite ^.*$ /index.html break;
    }
    access_log  /mnt/logs/nginx/access.log  main;
}

為什么要重寫路由?
因?yàn)槲覀兊捻椖恐挥幸粋€根入口,當(dāng)輸入類似/home的url時,如果找不到對應(yīng)的頁面,nginx會嘗試加載index.html,這是通過vue-router就能正確的匹配我們輸入的/home路由,從而顯示正確的home頁面,如果history模式的項目沒有配置上述內(nèi)容,會出現(xiàn)404的情況。

原問題鏈接:https://segmentfault.com/q/10...

2018年4月26日 03:12
編輯回答
浪婳

因?yàn)槟愕膎ginx配置是location /ocms/
這樣是無法匹配到/ocms請求的
建議配置改為

location /ocms {
    root /home;
    try_files $uri $uri/;
    #index  index.html index.htm;
}
2017年2月12日 10:51