Nginx部署Vue項目動態路由刷新404

前言

  • 記錄下Nginx部署Vue項目刷新404的解決方案,遇到了兩次,route用的是history路由模式,動態路由:
{
  path: '/article/:blogId',
  name: 'blog',
  component: blog
}
  • 然後部署nginx
location / {
	root   /usr/local/nginx/html/blog/;
    index  index.html index.htm;
}
  • 然後刷新頁面

在這裏插入圖片描述


  • what happend?

在這裏插入圖片描述

  • 後請教了度娘,度娘回答
 location / {
    root   /usr/local/blog/;
    index  index.html index.htm;
    try_files  $uri $uri/ /index.html;
}
  • 再然後

在這裏插入圖片描述


  • what happend?

在這裏插入圖片描述
在這裏插入圖片描述

好吧,記錄下兩次的解決方案,先行感謝兩位大佬給的啓發


第一次

網站沒有申請二級域名,部署了多項目,所以想的是添加項目前綴'/blog'訪問,比如這個:

https://www.coisini.club/blog
  • router.js
mode: 'history',
routes: [
  {
    path: '/blog', // 博客首頁
    component: home,
    children: [
      {
        path: '/',
        component: index
      },
      {
        path: '/blog/article/:blogId',
        name: 'blog',
        component: blog
      },
     ....
  • build.js
出錯打包配置
assetsPublicPath: './',

正確打包配置
assetsPublicPath: '/blog/',
  • 就是這個assetsPublicPath資源路徑忘記配置惹了N多麻煩, 留下了不學無數的眼淚,如果有遇到同樣場景的同學記得覈實

在這裏插入圖片描述

  • nginx.conf
有兩種配置方式,均驗證有效
方式一:
location /blog {
    root   /usr/local/nginx/html/;
    index  index.html index.htm;
    try_files  $uri $uri/ /blog/index.html;
}

方式二:
location /blog {
    root   /usr/local/nginx/html/;
    index  index.html index.htm;
    try_files $uri $uri/ @rewrites;
}

location @rewrites {
    rewrite ^/(blog)/(.+)$ /$1/index.html last;
}
  • LATER

在這裏插入圖片描述


第二次

網站申請了二級域名,之前的配置都要修改了,比如這樣:

https://blog.coisini.club/
  • router.js
mode: 'history',
routes: [
  {
    path: '/',
    component: index
  },
  {
    path: '/article/:blogId',
    name: 'blog',
    component: blog
  },
  ....
  • build.js
assetsPublicPath: './',
  • nginx.conf
server {
    listen       443 ssl;
    server_name  blog.coisini.club;
    
    location / {
        root   /usr/local/blog/;
        index  index.html index.htm;
    }
}
  • 然後部署

在這裏插入圖片描述
在這裏插入圖片描述

  • 然後照例請教度娘,度娘說try_files $uri $uri/ /index.html;
 location / {
    root   /usr/local/blog/;
    index  index.html index.htm;
    try_files  $uri $uri/ /index.html;
}
  • 然後

在這裏插入圖片描述

在這裏插入圖片描述

  • 然後,看了無數篇一毛一樣的博客後,找到了這位空虛公子vue部署在nginx後刷新404,雖然你腎虛,但我還是
    在這裏插入圖片描述

  • 正確的寫法:

  • build.js

assetsPublicPath: '/',
  • nginx.conf
location / {
    root   /usr/local/blog/;
    index  index.html index.htm;
    try_files  $uri $uri/ /index.html =404;
    autoindex  on;
}
  • LATER

在這裏插入圖片描述



- End -
- 個人筆記 -

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章