skip to Main Content

For a purpose of SEO i’ve been asked to add a slash at the end of every routes of my nuxt project. For example myapp.com/company should be myapp.com/company/ Is there a clean way to do that in Nuxt ?

3

Answers


  1. Chosen as BEST ANSWER

    ok i found the solution by writting a redirection in a middleware on serverside, so first i added to nuxt.config.js this :

    serverMiddleware: ["~/servermiddleware/seo.js"],
    

    then i created this file /servermiddleware/seo.js :

    const redirects = require('../301.json');
    module.exports = function (req, res, next) {
      const redirect = redirects.find(r => r.from === req.url);
      if (redirect) {
        console.log(`redirect: ${redirect.from} => ${redirect.to}`);
        res.writeHead(301, { Location: redirect.to });
        res.end();
      } else {
        next();
      }
    }
    

    and finally i write the redirections i want in 301.json in the root folder:

    [
      { "from": "/company", "to": "/company/" }
    ]
    

    edit: a problem stay here because inside the code of the app links stays without slash so the indexation of robot will use it.... i need to find a better solution.


  2. I am doing the requirement, too. I do the task with the following method, which I do not know it is right.

    Two steps:

    Nginx rewrite the url, that is to add slash of ‘/’ to the end of url, which the url isn’t ended with a slash. In this case, the http request is sent to the web server.

    At another case, if the request (or link routing) is routed at the front end, that the request does not send http request to the web server. Then add a middleware file called addSlash.js like this:

    function isThereSlashEnd(path) {
      let isSlash = true
      if (path) {
        let length = path.length
        isSlash = path[length-1] == '/' ? true : false
        console.log('??? path222: ', path, path[length-1], isSlash)
      }
      return isSlash
    }
    export default function({ req, store, route, redirect }) {
    
      /**
       * Add slash of '/' at the end of url
       */
      let isSlash = isThereSlashEnd(route.fullPath)
      console.log('??? path111: ', isSlash, route.fullPath, process.client)
      if (!isSlash) {
        if (process.client) {
          window.location.href = route.fullPath + '/'
          console.log('??? path: ', isSlash, route.fullPath, process.client, window.location)
        }
      }
    }
    

    With two steps above, get the task done.

    Login or Signup to reply.
  3. You can set trailingSlash to true in nuxt.config.js like below:

    router: {
        trailingSlash: true
    }
    

    For sitemap:

    sitemap: {
        hostname: 'https://www.mywebsite.com',
        trailingSlash: true,
    },
    

    Details more on https://dev.to/mornir/nuxt-netlify-and-the-trailing-slash-3gge

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search