Add _redirects file to root path for Vue SPA hosted on Netlify

后端 未结 5 858
难免孤独
难免孤独 2021-01-31 05:28

I\'m developing a Single Page App using Vue CLI and want history pushstate to work so I get clean URLs.

I have to follow this: https://www.netlify.com/docs/redirects/#hi

相关标签:
5条回答
  • 2021-01-31 05:46

    You could also just use the netlify.toml file which tends to be a bit cleaner. Just put this in the file to get the redirect you were looking for:

    # The following redirect is intended for use with most SPA's that handles routing internally.
    [[redirects]]
      from = "/*"
      to = "/index.html"
      status = 200
    

    You can find more info about the netlify.toml file here.

    0 讨论(0)
  • 2021-01-31 05:49

    You can simply add the _redirects file to your /public directory in your vue app

    0 讨论(0)
  • 2021-01-31 05:56

    vue-cli created app 3.x

    For the new build setup using the vue-cli version 3.0.0-beta.x there is a public folder now and you do not need the following setup. Just put your _redirects file under the public folder root. When you build it will make a copy to the dist folder which will be used for your deploy.

    vue-cli created app prior to 3.x

    Vue.js uses webpack to copy the static assets. This is maintained in webpack.prod.conf.js for the production build which is what you will need in this case for Netlify. I believe the best and cleanest configuration is based on this solution.

    Search the file for the new CopyWebpackPlugin in webpack.prod.conf.js.

    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.build.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
    

    Create a root ( folder in your project same level of the static folder ) You could name this anything you like, but I will use root for the example.

    You would then make sure the _redirects file is in the new root directory or whatever you called it. In this case it is named root

    Now modify the webpack.prod.conf.js CopyWebpackPlugin section to look like the following:

    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.build.assetsSubDirectory,
        ignore: ['.*']
      },
      {
        from: path.resolve(__dirname, '../root'),
        to: config.build.assetsRoot,
        ignore: ['.*']
      }
    ])
    
    0 讨论(0)
  • 2021-01-31 06:02

    Just in case you're looking for an answer on Nuxt instead of Vue, add the _redirects file to the static/ directory.

    0 讨论(0)
  • 2021-01-31 06:05

    I've tried Rutger Willems's snippet without the last line and it works. Credit goes to Hamish Moffatt.

    [[redirects]]
      from = "/*"
      to = "/index.html"
      status = 200
    
    0 讨论(0)
提交回复
热议问题