Different History modes

찌글렛·2022년 6월 9일
0

Vue

목록 보기
2/3

라우터 인스턴스를 생성할 때 옵션을 사용 history하면 다양한 기록 모드 중에서 선택할 수 있습니다.

해시 모드

해시 기록 모드는 다음으로 생성됩니다 createWebHashHistory().

import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    //...
  ],
})

#내부적으로 전달되는 실제 URL 앞에 해시 문자( )를 사용합니다 . URL의 이 섹션은 서버로 전송되지 않으므로 서버 수준에서 특별한 처리가 필요하지 않습니다. 그러나 그것은 SEO에 나쁜 영향을 미칩니다 . 그게 걱정된다면 HTML5 기록 모드를 사용하세요.

HTML5 모드

HTML5 모드는 다음으로 생성되며 createWebHistory()권장 모드입니다.

import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    //...
  ],
})

를 사용할 때 createWebHistory()URL은 "정상"으로 보입니다(예: https://example.com/user/id. 아름다운!

하지만 여기에 문제가 있습니다. 우리 앱은 적절한 서버 구성 없이 단일 페이지 클라이언트 측 앱이기 때문에 사용자가 https://example.com/user/id브라우저에서 직접 액세스하면 404 오류가 발생합니다. 이제 그것은 추한 것입니다.

걱정하지 마세요. 문제를 해결하려면 서버에 간단한 포괄 대체 경로를 추가하기만 하면 됩니다. URL이 정적 자산과 일치하지 않으면 index.html앱이 있는 동일한 페이지를 제공해야 합니다. 다시 한 번 아름답습니다.

메모리 모드

메모리 기록 모드는 브라우저 환경을 가정하지 않으므로 URL과 상호 작용하지 않으며 초기 탐색을 자동으로 트리거 하지 않습니다 . 이것은 Node 환경과 SSR에 완벽합니다. 로 생성되며 createMemoryHistory()를 호출한 후 초기 탐색을 푸시해야 합니다app.use(router) .

import { createRouter, createMemoryHistory } from 'vue-router'

const router = createRouter({
  history: createMemoryHistory(),
  routes: [
    //...
  ],
})

권장되지는 않지만 브라우저 응용 프로그램 내에서 이 모드를 사용할 수 있지만 기록 이 없으므로 뒤로 또는 앞으로 이동할 수 없습니다 .

서버 구성 예

참고 : 다음 예에서는 루트 폴더에서 앱을 제공한다고 가정합니다. 하위 폴더에 배포하는 경우 Vue CLI 옵션 과 라우터 관련 속성을 사용해야 합니다publicPath . 또한 루트 폴더 대신 하위 폴더를 사용하려면 아래 예를 조정해야 합니다(예: 로 대체 ) .baseRewriteBase /RewriteBase /name-of-your-subfolder/

아파치

<IfModule mod_negotiation.c>
  Options -MultiViews
</IfModule>

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

대신 을 mod_rewrite사용할 수도 있습니다 FallbackResource.

nginx

location / {
  try_files $uri $uri/ /index.html;
}

네이티브 Node.js

const http = require('http')
const fs = require('fs')
const httpPort = 80

http
  .createServer((req, res) => {
    fs.readFile('index.html', 'utf-8', (err, content) => {
      if (err) {
        console.log('We cannot open "index.html" file.')
      }

      res.writeHead(200, {
        'Content-Type': 'text/html; charset=utf-8',
      })

      res.end(content)
    })
  })
  .listen(httpPort, () => {
    console.log('Server listening on: http://localhost:%s', httpPort)
  })

Node.js로 표현하기

Node.js/Express의 경우 connect-history-api-fallback 미들웨어 사용을 고려하십시오 .

인터넷 정보 서비스(IIS)

  1. IIS UrlRewrite 설치
  2. web.config다음 을 사용하여 사이트의 루트 디렉터리에 파일을 만듭니다 .
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Handle History Mode and custom 404/500" stopProcessing="true">
          <match url="(.*)" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

캐디 v2

try_files {path} /
캐디 v1#
rewrite {
    regexp .*
    to {path} /
}

Firebase 호스팅

다음 항목에 추가 firebase.json:

{
  "hosting": {
    "public": "dist",
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}

네틀리파이

_redirects배포된 파일에 포함된 파일을 만듭니다 .

/* /index.html 200

vue-cli, nuxt 및 vite 프로젝트에서 이 파일은 일반적으로 static또는 public.

Netlify 문서 에서 구문에 대해 자세히 알아볼 수 있습니다 . 리디렉션 을 다른 Netlify 기능과 결합 하도록 만들netlify.toml 수도 있습니다.

베르셀

vercel.json다음 을 사용하여 프로젝트의 루트 디렉터리 아래에 파일을 만듭니다 .

{
  "rewrites": [{ "source": "/:path*", "destination": "/index.html" }]
}

경고

이에 대한 주의 사항이 있습니다. 찾을 수 없는 모든 경로가 이제 index.html파일을 제공하므로 서버에서 더 이상 404 오류를 보고하지 않습니다. 이 문제를 해결하려면 Vue 앱 내에서 포괄 경로를 구현하여 404 페이지를 표시해야 합니다.

const router = createRouter({
  history: createWebHistory(),
  routes: [{ path: '/:pathMatch(.*)', component: NotFoundComponent }],
})

또는 Node.js 서버를 사용하는 경우 서버 측 라우터를 사용하여 수신 URL을 일치시키고 일치하는 경로가 없으면 404로 응답하여 폴백을 구현할 수 있습니다. 자세한 내용 은 Vue 서버 측 렌더링 문서 를 확인하세요.

0개의 댓글