有关history路由原理以及为什么刷新会404请查看往期文章
这里不再赘述为什么404的原因。
其实如果这么理解,可能会更加容易些。服务器会请求你所填写的真实地址,比如/about-us/where-to-go
,会依次查找文件地址about-us、where-to-go
,但是vue项目和普通项目不同,这只是路由,并不是真的文件目录地址,所有的路由都是依赖于SPA单页应用的index.html。所以当刷新时,找不到对应产生404。
所以我们需要使用nginx的try_files,去查找index.html
.
nginx server配置
server {
listen 9002;
server_name localhost;
gzip on;
gzip_static on;
gzip_proxied any;
gzip_types
text/css
text/javascript
text/xml
text/plain
image/x-icon
application/javascript
application/x-javascript
application/json;
location / {
add_header Cache-Control no-store;
add_header Pragma no-cache;
add_header Expires 0;
root /home/test/;
try_files $uri $uri/ @router;
autoindex on;
}
location @router {
rewrite ^.*$ /index.html last;
}
location ~ ^/(images) {
add_header Cache-Control no-store;
proxy_pass http://localhost:8990;
}
}
try_files $uri $uri/ @router;
$uri 这个是nginx的变量,代表用户访问的单个文件地址。
比如:http://test.com/index.html, 那么$uri就是 /index.html。
$uri/ 这个代表用户访问的文件目录。
比如:http://test.com/index.html, 那么$uri就是 /index.html。
所以try_files $uri $uri/
的意思就是,比如http://test.com/example先去查找单个文件example,如果example不存在,则去查找同名的文件目录/example/,如果再不存在,将进行重定向@router
rewrite [regex] [replacement] [flag];
url正则表达式 替换成真实url 标记(last,break)
location @router {
rewrite ^.*$ /index.html last;
# 匹配所有 /index.html last;
}
凡是404的路由,都会被重定向到index.html,这样就显示正确了