Showing posts with label hash mode. Show all posts
Showing posts with label hash mode. Show all posts

Friday, January 14, 2022

How to remove hash mode(#) from URL in VueJs application

This is a quick tutorial on how we can get rid of hash mode(#) from the URL in the Vue.js application

While using Vue router, the default mode is a hash mode. So when the user tries to load the page like http://localhost:8080/invalid/url then it will redirect to the base URL with hash.

We can simply remove hash mode by adding history mode while initializing the Vue router

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

This initialization can be found under folder >> src >> router >> index.js if we initialized the application with router setup using Vue CLI. Or in main.js file.

Once we remove the hash mode the user with an invalid URL might get a 404 not found error. For this, we need to manage the configuration in the server where we deploy the application.

For this, we need to configure in such a way that for the invalid users, we will redirect the user to index.html page which will open the base URL of the application.

In Nginx

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

In Apache

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

In Firebase inside firebase.json add the following JSON config

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

For more server configuration please visit the vue-router page.

Share: