详解nginx配置vue h5 history去除#号

(编辑:jimmy 日期: 2024/12/23 浏览:2)

vue的默认配置是使用hash模式,这样我们访问的时候都带有了一个#号,再支付回调的地址或者其他原因不支持#号或者不喜欢#号这种模式,优势就出现了需要去除#号,于是vue端就需要配置该模式,并且使用懒加载,vue端的配置如下:

首先先声明一下,这是使用vue+nginx实现前后端分离的项目,并且使用vue axios实现代理功能(允许跨域并且服务端已经开启跨域),

详解nginx配置vue h5 history去除#号

然后就是打包的配置:

详解nginx配置vue h5 history去除#号

!!!注意,这里配置的assetsPublicPath一定要配置成  "/"  而不是  "./"之类的,不然nginx服务端即使配置成为了vue h5 history模式,也会出现如下错误:

Uncaught SyntaxError: Unexpected token <
manifest.16a4233693dc526194f6.js:1 Error: Loading chunk 23 failed.
  at HTMLScriptElement.t (manifest.16a4233693dc526194f6.js:1)
d.oe @ manifest.16a4233693dc526194f6.js:1
Promise.catch (async)
component @ app.a879af571e30c08073af.js:1
(anonymous) @ vendor.8f8ebced8a21d4a0633a.js:6
(anonymous) @ vendor.8f8ebced8a21d4a0633a.js:6
(anonymous) @ vendor.8f8ebced8a21d4a0633a.js:6
ve @ vendor.8f8ebced8a21d4a0633a.js:6
(anonymous) @ vendor.8f8ebced8a21d4a0633a.js:6
h @ vendor.8f8ebced8a21d4a0633a.js:6
i @ vendor.8f8ebced8a21d4a0633a.js:6
i @ vendor.8f8ebced8a21d4a0633a.js:6
(anonymous) @ vendor.8f8ebced8a21d4a0633a.js:6
(anonymous) @ vendor.8f8ebced8a21d4a0633a.js:6
(anonymous) @ app.a879af571e30c08073af.js:1
h @ vendor.8f8ebced8a21d4a0633a.js:6
i @ vendor.8f8ebced8a21d4a0633a.js:6
i @ vendor.8f8ebced8a21d4a0633a.js:6
i @ vendor.8f8ebced8a21d4a0633a.js:6
pe @ vendor.8f8ebced8a21d4a0633a.js:6
_e.confirmTransition @ vendor.8f8ebced8a21d4a0633a.js:6
_e.transitionTo @ vendor.8f8ebced8a21d4a0633a.js:6
t.push @ vendor.8f8ebced8a21d4a0633a.js:6
Pe.push @ vendor.8f8ebced8a21d4a0633a.js:6
b @ vendor.8f8ebced8a21d4a0633a.js:6
t @ vendor.8f8ebced8a21d4a0633a.js:12
Fi.t._withTask.s._withTask @ vendor.8f8ebced8a21d4a0633a.js:12
vendor.8f8ebced8a21d4a0633a.js:6 Error: Loading chunk 23 failed.
  at HTMLScriptElement.t (manifest.16a4233693dc526194f6.js:1)

所以,请谨慎配置,坑比较多,下面就是nginx服务端的配置了,

server {
    listen    80 default_server;
    listen    [::]:80 default_server;
    server_name _;
    root     /usr/share/nginx/dist;

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    #根据路由设置,避免出现404
    location ^~ /api/ {
        add_header 'Access-Control-Allow-Origin' '*';
        proxy_pass http://service.xxxx.com/;
    }
    location / {
      try_files $uri $uri/ @router;#需要指向下面的@router否则会出现vue的路由在nginx中刷新出现404
      index index.html index.htm;
    }
    #对应上面的@router,主要原因是路由的路径资源并不是一个真实的路径,所以无法找到具体的文件
    #因此需要rewrite到index.html中,然后交给路由在处理请求资源
    location @router {
      rewrite ^.*$ /index.html last;
    }
    error_page 404 /404.html;
      location = /40x.html {
    }

    error_page 500 502 503 504 /50x.html;
      location = /50x.html {
    }
  }

这样配置就算是配置好了,然后就不会出现页面刷新显示404的错误了。