Reputation: 609
I have a website that I have rebuilt using Nuxt 3. Backlinks exists on numerous platforms and I need the old links to point to the new pages. Example: old(website.com/contact.html) new(website.com/contact)
I tried using middleware, but after deploying it, I get this error: 502 Error decoding lambda response
In my middleware/redirect folder I have this:
const redirects = [{
'from' : '/contact.html',
'to' : '/contact'
}]
export default function (req, res, next) {
const redirect = redirects.find((r)=> r.from === req.url)
if (redirect) {
res.writeHead(301, { Location: redirect.to })
res.end()
} else {
next()
}
}
It works locally but not after deploying to netlify!
and I added this to my nuxtconfig file:
serverMiddleware: [
'~/middleware/redirect'
]
I thought that this middleware would act as a net to catch any req to the old contacts.html page and redirect them to the new contact page. but instead it sends that lambda error which I looked around and have not found a solid fix for. I am open to any solution including a different way of redirecting! Thank you!
Upvotes: 18
Views: 23375
Reputation: 3740
Instead of building your own middleware, you can add your own router options. Here are the docs.
app
in the root of your project (same folder as nuxt.config.ts
./app
create file router.options.ts
.router.options.ts
write:import type { RouterOptions } from '@nuxt/schema';
// https://router.vuejs.org/api/interfaces/routeroptions.html
export default <RouterOptions>{
routes: (_routes) => [
{
name: 'contact',
path: '/contact',
component: () => import('~/pages/contact.vue'),
alias: '/contact.html',
},
],
};
EDIT:
You could also use definePageMeta
with alias
. Docs.
Upvotes: 2
Reputation: 2287
You can achieve redirections without middlewares by using the redirect
option inside routeRules
in nuxt.config.ts
as below:
export default defineNuxtConfig({
routeRules: {
'/contact.html': { redirect: '/contact' },
'/external-route': { redirect: 'https://example.com' },
},
})
you can also define a new route that can be redirected to any internal or external page.
More rules options can be found here: https://nitro.unjs.io/config/#routerules, which mentioned in the official doc
Upvotes: 21