vue項目線上頁面刷新報404 解決方法
在上線vue開發的前端網頁上線后,刷新頁面報404錯誤,因為網頁上顯示的是靜態絕對路徑,實際上服務器上是沒有改路徑的所以刷新匯報錯誤。
1、vue框架中解決404
vue router mode 默認為hsas, 這樣的url中帶有#,如果把mode: 'history'就能去掉#號,也可以正常訪問,但是再次刷新頁面就會出現404錯誤。
const router = new Router({
mode: 'history'
});
url中帶有#,讓有強迫症的人很不爽,可以去掉,去掉后就需要改nginx配置文件了。
2、修改nginx配置文件
1
2
3
4
5
|
location / {
root ...
index ...
try_files $uri $uri/ /index.html; ---解決頁面刷新404問題
}
|
將上面代碼放入nginx配置文件中
保存退出
. ./nginx -t -- 驗證nginx配置文件是否正確
. ./nginx -s reload -- 重啟nginx
記得修改完nginx配置文件一定要重啟nginx 不然沒有效果!!!
親自試驗截圖:可以訪問
Nginx--try_files 解釋
1
2
3
4
5
6
7
8
9
|
location / {
root /
var
/www/build;
index index.html index.htm;
try_files $uri $uri/ @rewrites;
}
location @rewrites {
rewrite ^(.+)$ /index.html last;
}
|
這句話是什么意思?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
server {
listen 80;
server_name localhost;
root html/;
index index.html index.htm index.php;
location / {
try_files $uri $uri/ /index.php?$args;
proxy_pass http:
//www.baidu.com;
}
location ~ \.(html|htm)$ {
try_files $uri = 404;
}
location ~ \.php$ {
try_files $uri = 404;
include fastcgi.conf;
fastcgi_pass 127.0.0.1:9000;
}
}
|
try_files
這個東西是重定向用的,我感覺和index 差不多,不過確實比index 要好用
舉個例子:
訪問:xf.com/aa
如果我們這么設置,對於這一句的理解是。
try_files uriuriuri/ /index.php?$args;
當nginx 收到你的xf.com/aa ,那么會匹配到
location / {
try_files uriuriuri/ /index.php?$args;
proxy_pass http://www.baidu.com;
}
這里多說一嘴,如果沒有合適的匹配,那么就會找index的值。
index.html inde.htm index.php
當找到相對應的文件,就會把你的訪問url變成。
xf.com/index.html或者xf.com/index.htm xf.com/index.php 其中一個
這回你明白index了吧
回來我們再說 try_files
當匹配到這項的時候,就開始執行try_files
nginx 回去找有沒有 aa這個文件($uri) 如果沒有
繼續找aa這個目錄($uri/) 如果也沒有的話就直接
重定向到 /index.php?$args
$args 就是你的url 問號后邊的參數