Is there rewrites in middleware?
What I need to do is rewrite from website.com/rooms/:country/:region/:city to website.com/:country/:region/:city
7 Replies
Hi @salomon_.. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
Yes, you can implement URL rewrites in Nuxt using middleware. Based on the knowledge sources, there are a few approaches to handle your specific case of rewriting from
website.com/rooms/:country/:region/:city
to website.com/:country/:region/:city
.
Using Route Middleware
You can create a route middleware to handle the rewrite:
You can place this in your middleware
directory, for example as middleware/rewrite.js
and then apply it globally by naming it rewrite.global.js
or selectively on specific pages using definePageMeta
as described in the documentation.
Important Considerations
1. The navigateTo
function allows you to specify a redirect code (301 for permanent redirects or 302 for temporary redirects) as mentioned in the middleware documentation.
2. If you need more complex rewriting logic, you might want to consider using Nitro server middleware which runs on the server side before the Vue application is initialized.
3. For production deployments, especially on platforms like Netlify, you might need to configure additional settings as server-side redirects can behave differently than in local development as seen in some user experiences.
Remember that middleware in Nuxt runs in a specific order: global middleware first, followed by page-defined middleware as documented here.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@1029431292170874910> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
I'd do that in nitro though, not in a route middleware
Hi, how would you do it? I couldn't find rewrites in nitro docs too. In nextjs for example, I did this with
NextResponse.rewrite
.
Basically what I need to do is: the url should be website.com/:country/:region/:city
but it should match pages/hotels/[...slug].vue
component (route). Is that possible?ah, that's a different task. I thought you want to rewrite and just replace
/rooms
So nuxt miss this feature?
no no, I mean you can still validate the parts of your URL via
...slug
and render a different component for example