Search code examples
javascripthttp-redirectshopifygoogle-search-console

Return 301 status code while redirecting URLs Via JavaScript code


I want to redirect product recommendation string query URLs to non-string query URLs in Shopify and also want that they should return 301 status code while redirecting.

For example from this URL: https://ese.net/products/some-product?pr_prod_strat=collection_fallback&pr_rec_id=503f88472&pr_rec_pid=8474186613075&pr_ref_pid=8461060833619&pr_seq=uniform

To this: https://ese.net/products/some-product

I've tried to add redirect in 301 redirection manager of Shopify but the redirection not worked for string query URLs. redirect setup in shopify but not worked

Then I've added the JavaScript code in theme.liquid file to redirect string query URLs to non-string query URLs. It worked but its not returning 301 status code while redirecting. I want that when it redirect via JavaScript it should return 301 status code or also share if there is any other method to redirect them.

Redirection preview

<script>
  document.addEventListener('DOMContentLoaded', function() {
    var url = new URL(window.location.href);
    var params = new URLSearchParams(url.search);

    if (params.has('pr_prod_strat')) {
      // Remove the query string from the URL
      url.search = '';
      // Redirect to the URL without query string
      window.location.replace(url.toString());
    }
  });
</script>

Solution

  • You can't do a 301 redirect in JavaScript. It is a status code for a response from the server.

    If this is for SEO, make sure the pages canonical tag is for the URL without the parameters. That's the next strongest signal to search engines.

    If you just want users to not see the ugly url, just change it in the address bar. History state does that I think.

    If you really want to redirect the user to the page without the parameters, you can in JavaScript. It is not 301 redirect, it's a JavaScript redirect, but search engines typically treat it the same.