How to add redirects on Search?

In the case you've built specific landing pages to display search results, it becomes really handy to be able to redirect users to those dedicated pages in the case their search query matches one of those.

### Example Let's say you have an e-commerce website where you sell "star wars" related goods, and you'd like to redirect the user searching for "star wars" (or any related words) to a shiny Star Wars page.

No problem, that can be easily done in a few steps:

1Create a new index that will contain all the redirection rules. _We can, for instance, name it 'redirects'._

2Add to that index records containing the URL of the landing page and an array of keywords that will trigger the redirection.

{
  "url": "https:// ....",
  "query_terms": ["star wars", "jedi", "darth vader", "george lucas", "luke skywalker"]
}

3Configure the index settings:

  • Add the 'query_terms' attribute to the attributesToIndex list.

    If _the query terms order doesn't matter, _set the attribute to 'unordered'.

  • Set the Typo Tolerance to min

  • Enable the ignorePlural option

  • Enable the removeWordsIfNotResults option and set it to 'allOptional'

4Implement a small business logic on the client side:

  • At each new keystroke in the search field, perform a search against that index to retrieve a single result (hitsPerPage=1).

If you're using Javascript, you can find more details about the way to call multiple indices at the same time at https://github.com/algolia/algoliasearch-client-js#multiple-queries

  • When the user presses enter (or clicks on the search icon) and if there is a result returned by that search query, use the "url" value to redirect the user to the correct page.

Happy coding! If you have any question, feel free to reach out to our support!

Last updated