Vue study notes: The difference between History routing and Hash routing and the configuration method of Nginx in History mode

1. History mode, Hash mode

  Vue Router is the official routing manager of Vue.js, used to build front-end routing for single-page applications. It allows you to map different URLs to corresponding components by defining routing configurations to achieve jumps and navigation between pages. Vue Router supports two routing modes: history mode and hash mode.

1. History mode

  ˜In History mode, Vue Router manages routing by using the HTML5 History API and does not use hash (#) in the URL as a routing tag. Instead, it relies on the browser's History API to manage URL changes.

  Using History mode requires the cooperation of the backend server. When a user directly accesses a page in the browser, or refreshes the page, the backend server needs to be configured to ensure that the corresponding front-end routing page is returned. This is because in History mode, the front-end routing and the back-end routing are separated, and the back-end needs to redirect all routing requests to the front-end entry page.

  • When using history mode, there is no # symbol in the URL.
  • Change the URL through HTML5 History API (pushState and replaceState) to implement front-end routing jump.
  • The server needs to be configured accordingly to ensure that when refreshing the page or directly accessing a sub-route, it can still correctly return the page corresponding to the front-end route.
  • Example URL: https://example.com/my-route
2. Hash mode

  Hash mode is a simple and common routing mode in Vue Router, which uses hashes (#) in URLs to manage routing. When the hash value in the URL changes, Vue Router will match the corresponding route based on the hash value.

  • When using hash mode, there will be a # symbol in the URL, followed by the routing path.
  • Change the hash value in the URL by listening to the hashchange event to implement front-end routing jump.
  • No special configuration of the server is required because changes to the hash portion are not sent to the server.
  • Example URL: https://example.com/#/my-route
3. The difference between History mode and Hash mode
  1. History mode URLs are more beautiful and cleaner, more similar to traditional URL structures.
  2. Hash mode URLs have good compatibility, do not require special server configuration, and can be used in almost all environments.
  3. When using History mode, you need to ensure that the server-side configuration is correct so that the corresponding page can be returned correctly when refreshing the page or directly accessing the sub-route. Hash mode does not require such configuration.

  In short, the History mode URL may be more in line with users' habits, but it requires server configuration. Hash mode is simpler and easier to use, but there will be a # symbol in the URL. Choosing which routing mode to use depends on your project needs and server environment.

2. Nginx server configuration when using History mode

  In History mode, the server needs to be configured accordingly to ensure that the page corresponding to the front-end route can still be correctly returned when refreshing the page or directly accessing a sub-route. When using an Nginx server, you can use the try_files configuration to redirect all requests to the front-end entry page. At the same time, relevant configurations also need to be added in the vue project to ensure that the routing address is correct. The specific implementation is as follows:

  First of all, the main.js file needs to introduce router routing. The code is as follows:

import Vue from 'vue'
import App from './App.vue'
import router from "./router/index";

Vue.config.productionTip = false

new Vue({
    
    
	router,
  render: h => h(App),
}).$mount('#app')

  Then, the App.vue file, basic configuration, does not require special processing, the code is as follows:

<template>
  <div id="app">
    <h1>APP B</h1>
	<router-view></router-view>
  </div>
</template>

<script>

export default {
    
    
  name: 'App'
}
</script>

<style>

</style>

  Then, modify the routing configuration file ./router/index.js. In this file, we configure the History mode, and also need to configure the base path to ensure correct routing access. The code is implemented as follows:

import VueRouter from 'vue-router';
import Hello from "../components/Hello.vue"
import Vue from "vue";

Vue.use(VueRouter)
const router = new VueRouter({
    
    
	mode: 'history',
	base:'/app2/',
    routes:[
        {
    
    
            path: '/hello',
            name: 'hello',
            component: Hello
        },
    ],
})

export default router;

  Then, modify the packaging configuration file vue.config.js. Here you need to ensure that the publichPath matches the above-mentioned baseUrl, and the corresponding project is deployed at the secondary directory address "/app2/" on the server.

module.exports = {
    
    
  transpileDependencies: ["vue"],
  publicPath: '/app2/', // 设置上下文路径,与Tomcat或Nginx中的上下文路径保持一致
  indexPath: 'index.html', // 相对于打包路径index.html的路径
  outputDir: process.env.outputDir || 'app2', // 'dist', 生产环境构建文件的目录
  devServer: {
    
    
    headers: {
    
    
      'Access-Control-Allow-Origin': '*',
    }
  }
};

  Finally, modify the Nginx configuration file nginx.conf and use try_files to redirect all requests to the front-end entry page. The configuration is as follows:

server {
    
    
      listen       8000;
      server_name  192.168.1.87;
	  root   html;
      location /app2 {
    
    
	     try_files $uri $uri/ /app2/index.html;
      }
}

  According to the above configuration, our front-end page location should be deployed in ./html/app2/ in the nginx root directory. At this point, we can use History mode routing normally.

Guess you like

Origin blog.csdn.net/hou_ge/article/details/131572314