skip to Main Content

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>

2

Answers


  1. I would suggest correcting this in the .liquid template rather than in javascript.

    Here’s how to strip url params in liquid:

    {%- liquid
        assign clean_url = product.url
        assign has_params = false
        if product.url contains '_pos=' or product.url contains '_ss=' or product.url contains 'pr_prod_strat=' or product.url contains 'pr_rec_id=' or product.url contains 'pr_ref_pid=' or product.url contains 'pr_seq='
            assign clean_url = clean_url | split: '?' | first
            assign has_params = true
        endif
    -%}
    
    <a {% if has_params %} href="{{ clean_url }}"{% else %} href="{{ product.url }}"{% endif %}>{{ product.title }}</a>
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search