如何在 Next.js 中添加 301 重定向(从 http 到 https)? [英] How to add 301 redirection ( from http to https ) in Next.js?

查看:10
本文介绍了如何在 Next.js 中添加 301 重定向(从 http 到 https)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Next.js 中添加 301 重定向(从 http 到 https)?

How to add 301 redirection ( from http to https ) in Next.js?

例如 - 来自这个http://stackoverflow.com/"到这个https://stackoverflow.com/"?

For example - from this "http://stackoverflow.com/" to this "https://stackoverflow.com/" ?

推荐答案

你可以通过 _app.js 来实现,这样做:

You can do it from _app.js, by doing this:

res.writeHead(301, { Location: `https://${req?.headers.host}/${asPath}` })

如果您有 forvarded-proto 标头,那么您还可以检查:

If you have forvarded-proto header then you can also check:

req.headers['x-forwarded-proto'] === 'http'

否则你必须自己判断是在http还是https,例如你可以尝试解析url:

Otherwise you must determine if you are at http or https by yourself, as an example you can try parsing the url:

const url = new URL('http://example.com')
console.log(url.protocol) // output: "http:"

这篇关于如何在 Next.js 中添加 301 重定向(从 http 到 https)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆