vue项目history路由,F5刷新页面,页面404问题,nginx try_files解决方案

有关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,这样就显示正确了

Vue 路由history 模式下,刷新页面会导致 404 错误的出现,这是因为浏览器会向服务器发送请求,但服务器并没有对应的路由,因此就会返回 404 错误。解决这个问题的方法有两种: 1. 配置后端服务器 如果你的 Vue 项目部署在 Apache 或 Nginx 等 Web 服务器上,你可以配置服务器来处理这个问题。具体做法是,在服务器上配置一个重定向规则,将所有的 URL 请求都重定向到 index.html 文件上。以 Apache 服务器为例,可以在 Apache 的配置文件(如 httpd.conf)中添加以下规则: ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] </IfModule> ``` 这个配置将所有的 URL 请求都重定向到 index.html 文件上,这样即使刷新页面,服务器也会返回正确的内容。 2. 使用 hash 模式 如果你不想在服务器上配置重定向规则,你可以考虑使用 hash 模式。在 hash 模式下,Vue 会使用 URL 中的 # 符号来表示路由,这样即使刷新页面,浏览器也只会重新加载 index.html 文件,而不会向服务器发送请求。要启用 hash 模式,只需要在 Vue 路由的配置中添加以下代码: ``` const router = new VueRouter({ mode: 'hash', routes: [...] }) ``` 这样就可以启用 hash 模式了。需要注意的是,hash 模式下,URL 中的 # 符号后面的内容不会被发送到服务器,因此你需要在前端代码中使用 JavaScript 来解析 URL 中的 hash 值,并根据这个值来渲染不同的页面
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值