仔细看我下面所说,每一步都是坑
1.页面刷新404 Not Found
(1)问题原因
web单页面开发模式,只有一个index.html入口,其他路径是前端路由去跳转的,nginx没有对应这个路径,所以就会报404了
(2)解决方法
增加try_files $uri $uri/ /index.html配置;意思就是如果第一个存在,直接返回;不存在的话读取第二个index.html
location / {
try_files $uri $uri/ /index.html;
}
2.页面刷新以后403 Forbidden
![](https://img-blog.csdnimg.cn/af3687f2b2ab475fb9bc2de759909fb4.png)
![](https://img-blog.csdnimg.cn/ac28ecc0a69747e2a5cca611e724508a.png)
(1)问题原因
情况1.vue-router里面的导航守卫beforeEach和afterEach这里面设置了跳转
情况2.页面刷新会报错误
原因:这里的路由跳转相当于从新请求了一下nginx代理的路由,但是nginx没有所以失败
(2)解决方法(我用的下面代码中的例子1解决的)
在nginx里面配置路由地址重写(重定向)rewrite
例1:访问www.a.com/a.html------->www.a.com/b.html
vim /usr/local/nginx/conf/nginx.conf
server {
listen 80; #端口
server_name www.a.com; #虚拟主机
rewrite /a.html /b.html; #www.a.com/a.html www.a.com/b.html
location / {
root html; # documentRoot
index index.html index.htm; # 默认是index.html页面
}
}
还需要配置域名www.a.com,可以通过配置dns或者修改/etc/hosts
例2:访问192.168.4.20------->www.baidu.com
vim /usr/local/nginx/conf/nginx.conf
server {
listen 80; #端口
server_name localhost; #虚拟主机
rewrite ^/ http://www.baidu.com; #其中^代表正则表达式,^/表示所有路径
location / {
root html; # documentRoot
index index.html index.htm; # 默认是index.html页面
}
}
例3:访问192.168.4.20/xxxxx------->www.baidu.com/xxxxx
vim /usr/local/nginx/conf/nginx.conf
server {
listen 80; #端口
server_name localhost; #虚拟主机
rewrite ^/(.*) http://www.baidu.com/$1; #其中^代表正则表达式,^/(.*)表示提取所有路径,然后通过$1使用匹配到的路径
location / {
root html; # documentRoot
index index.html index.htm; # 默认是index.html页面
}
}
例4:实现不同的浏览器访问192.168.4.20/test.html返回不同的页面
这里咱们使用curl浏览器和firefox浏览器。curl是一款没有图形的浏览器,只可以显示代码信息。
这个403问题改了好久
尝试过挣扎的方法
1.试图阻止页面刷新 失败
2.试图阻止路由重定向 失败
3.试图前端修改url路径然后跳转到可以使用的链接的情况 失败
感觉这个文章好的话,给个赞,顺便评论666 栓Q了