How to drop the get arguments after redirects

Hello,

On my website (with configs described there: Website broken after upgrading to latest · Issue #1490 · netlify/next-runtime · GitHub ) I would like to have a page redirecting without keeping the GET parameters:

/blog/:id should not changed
/blog?a=:id should redirect to /blog/:id
/blog/:id?a=:a should redirect to /blog/:id
/blog should redirect to /publicPresence

as explained here (Website broken after upgrading to latest · Issue #1490 · netlify/next-runtime · GitHub) it works locally with my settings but not once deployed.

Thank you for your help !

Hey @leob_123,

I believe you should be able to get it working like:

[[redirects]]
  force = true
  from = "/blog"
  status = 301
  to = "/publicPresence"
[[redirects]]
  force = true
  from = "/blog/*"
  status = 301
  to = "/.netlify/functions/redirect/"
  [redirects.query]
    a = ":a"

Inside the redirect function:

export async function handler(event) {
  return {
    headers: {
      location: `/blog/${event.queryStringParameters.a}/?param=true`
    },
    statusCode: 301
  }
}

Note that, I’ve directly typed this without testing, so if something doesn’t work, feel free to revert.

As I’ve mentioned on the issue, I’d recommend using Edge Functions for a task like this due to its speed considerations, but you’re free to use Functions.

that is not working for me :confused:

Hey there, @leob_123 :wave:

Thanks for following up! When you mention “that is not working for me” can you elaborate on which suggestions you tried? Having additional details will help us as we continue to make suggestions. Additionally, did you try using edge functions as Hrishikesh suggested?

I tried the one solution present in this post and it does not work :slight_smile:

Hi @leob_123

Sure, edge functions are in beta, but that doesn’t mean they aren’t a viable option. The more people use them, the more (potential) issue are found and rectified and the quicker they may make it to prime time.

For an edge function, you might try something like this simple script to strip the search string completely

export default async({url}) => {
  const to = new URL(url)
  to.search = ""
  return new Response(null, {
    status: 301,
    headers: {
      Location: to.href
    }
  })

}

NOTE: This is only useful if there are no other search param that need keeping.

If you wish to use a standard serverless function then this is the equivalent of the edge function above

exports.handler = async (event) => {
  const to = new URL(event.rawUrl)
  to.search = ''
  return {
    statusCode: 301,
    headers: {
      Location: to.href
    },
  }
}