Custom Size – 1.

Shopify: How to implement one-to-one redirects with Liquid

Hi.
I am Takasaki, President and CTO.
I can't believe two-thirds of it is over again this year.

Now, it's real, but Shopify originally had the ability to redirect from a management screen, and if you are a normal redirect then this function is fine.
However, this feature does not allow you to “redirect a public product URL to another domain URL”.

However, although we operate the site in a headless commerce format, since URLs that are spit out by various sales Chanel-linked apps have become URLs of online shops made with Shopify themes, if you want to redirect them to the headless side etc.
In this article, I will explain how to do such a case.

The code we're going to discuss is JS, and it's a one-on-one redirect on the client side.
If your page URL is changed and redirected, it’s better to do 301 redirection on the server side for SEO reasons, so please call from the Shopify management screen.

what someone wants to do

and we've created an online shop called example.com
I’d like to redirect to a headless commerce site that was built on new-example.
However, I want to display the account-related page as it is in Liquid.

 method

Described in the head tag inside layout/theme.

The account page you do not want to redirect is obtained from the template variable as follows and judged.
The following is an if statement that excludes the account page.

{% if template != 'cart' and template != 'customers/account' and template != 'customers/activate_account' and template != 'customers/addresses' and template != 'customers/login' and template != 'customers/order' and template != 'customers/register' and template != 'customers/reset_password' %}

Declarate the new domain as a variable.

{% assign new_website = 'https://new-example.com' %}

Add the following JS code under that declaration and redirect it to one-on-one.

     <script>
        function getCookie(name) {
          name = name + '=';
          var cookies = document.cookie.split(';');
          for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].trim();
            if (cookie.indexOf(name) == 0) {
              return cookie.substring(name.length, cookie.length);
            }
          }
        }

        // ディスカウントコードがあった場合をそれを維持ししたままJSでリダイレクトをかける
        var discountCode = getCookie('discount_code');
        if (discountCode) {
          window.location.replace(`{{new_website}}/discount/${discountCode}?redirect=${window.location.pathname}`);
        } else {
          let path = window.location.pathname;
          window.location.replace(`{{new_website}}${path}`);
        }
      </script>

That's all.
and it's safe to say
https://example.com/〇〇
but
https://new-example.com/〇〇
It is redirected to.

If you want to systematically learn about Liquid development, we are here. Shopify Development Document Please also refer to it.
Let’s all have a good Shopify life.

article category