【问题标题】:How to make redirect from www to non-www in nuxt.js如何在 nuxt.js 中从 www 重定向到非 www
【发布时间】:2024-01-11 22:29:01
【问题描述】:

谁知道如何在 nuxt.js 中进行从 www 到非 www 的重定向?

提前致谢。

【问题讨论】:

  • 请详细说明。对于重定向,您有 nuxt-link 或带有 href 或路由器推送的锚标记
  • @HardikShah,我有一个关于 nuxt.js(通用模式)的项目,我想在每次用户打开带有 www 的链接时进行重定向,例如(www.example.com)到非 www网址(example.com)

标签: redirect nuxt.js server-side-rendering


【解决方案1】:

Incase any 仍然有这个问题。

我不得不使用这篇文章用 CloudFlare 解决它 https://support.cloudflare.com/hc/en-us/articles/200172286-How-do-I-perform-URL-forwarding-or-redirects-with-Cloudflare-

你也可以用 serverMiddleware 来实现 https://nuxtjs.org/docs/2.x/configuration-glossary/configuration-servermiddleware#custom-server-middleware

创建一个文件并粘贴以下代码。

module.exports = function (req, res, next) {
  const host = req.headers.host
  const url = req.url
  const env = process.env.NODE_ENV
  const forceDomain = 'https://masteringbackend.com'

  if (env === 'production' && host !== 'www.masteringbackend.com') {
    res.writeHead(301, { Location: forceDomain + url })
    return res.end()
  }

  return next()
}

然后你在serverMiddleware注册文件

另一种方式

您可以查看https://mindthecode.com/blog/how-to-redirect-www-traffic-to-non-www-in-your-express-app/,但请记住 res.redirect 仅用于 Express,在 Connect 中进行重定向(纯 node.js http):Response redirect in Connect

【讨论】: