服务器配置示例
部署到Nginx如何没有配置上面这段代码,刷新的时候会出现404 not Found nginx。项目之前vue-router使用默认
hash模式,在本地与部署线上环境后都没有问题,因为hash模式带有#有点不太美观,所以后来选择用history模式,再次部署到线上环境Nginx环境后,能正常访问,切换路由也没任何问题,但是当刷新页面后,就会出现404 not found nginx字样,页面没有出来。
nginx
部署到nginx vue-router history 模式下的配置需要添加以下代码
location / {
try_files $uri $uri/ /index.html;
}
问题深究
出现以上问题,是因为Nginx配置的根目录/www/wwwroot/xxx/dist下面压根没有'/dashboard'或者一些我们路由的写法的路径。
server
{
listen 80;
server_name xxx.com;
index index.php index.html index.htm default.php default.htm default.html;
root /www/wwwroot/xxx/dist;
...
}
然而那些路由没有存在在dist文件夹目录下,比如dashboard文件没有存在在目标目录下,所以当刷新时自然是404.
在传统的hash模式中(http://localhost#dashboard),即使不需要配置,静态服务器始终会去找index.html并返回来,然后vue-router会获取#后面的字符作为参数,对前端页面进行交换。
类比一下,在history模式中,我们所想要的情况就是:输入http://localhost/dashboard,但最终返回的也是index.html,然后vue-router会获取dashboard作为参数,对前端页面进行交换。那么在Nginx中,谁能做到这件事呢?答案就是try_files
try_files
try_files file ... uri;
- 按指定的
file顺序查找存在的文件,并使用第一个找到的文件进行请求处理 - 查找路径是按照给定的root或alias为根路径来查找的
- 如果给出的file都没有匹配到,则重新请求最后一个参数给定的uri,就是新的location匹配
比如:
location /images/ {
root /opt/html/;
try_files $uri $uri/ /image/default.gif;
}
比如 请求 127.0.0.1/images/test.gif 会依次查找 1.文件/opt/html/images/test.gif 2.文件夹 /opt/html/images/test.gif/下的index文件 3. 请求127.0.0.1/images/default.gif
解释 try_files $uri /index.html
server
{
listen 80;
server_name xxx.com;
index index.php index.html index.htm default.php default.htm default.html;
root /www/wwwroot/xxx/dist;
try_files $uri $uri/ /index.html; // 解释如下
...
}
$uri 是Nginx中的变量,比如(http://localhost/dashboard),那么它就代表/dashboard
在/www/wwwroot/xxx/dist这个目录下,没有子目录,只有一个index.html和一些压缩后的名称是hash值的.js文件,当我们请求http://localhost/dashboard这个地址时,首先先找有没有dashboard这个文件,没有;再找有没有dashboard这个目录,也没有;那么最终会定位到第三个参数从而返回index.html,按照这个规则,所有路由里的url路径最后都会定位到index.html。
vue-router再获取参数进行前端页面的交换。那么就是获取/dashboard进行页面交换,这个时候就可以成功访问到了。
uri/在这个例子中没多大用处,实际上可以去掉。