Редирект и блокировка по языку

Справка

Данный скрипт блокирует нежелательные IP адреса на клиенте по языку браузера пользователя. Второй скрипт направляет пользователя на нужную версию сайта по языку его браузера.

Редирект по языку

/ru/*    /ru/index.html   200
/en/*    /en/index.html   200
/*       /index.html      200

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Redirecting...</title>
    <script>
      (function () {
        // Проверяем, не выбрал ли пользователь язык ранее
        const storedLang = localStorage.getItem("preferredLang");

        // Проверяем, не находится ли уже на /ru или /en
        const pathname = window.location.pathname;
        const isAlreadyLocalized =
          pathname.startsWith("/ru") || pathname.startsWith("/en");

        if (storedLang && !isAlreadyLocalized) {
          // Пользователь уже выбрал язык ранее — редиректим на него
          window.location.href = "/" + storedLang;
          return;
        }

        if (!storedLang && !isAlreadyLocalized) {
          // Первый визит — определяем язык браузера
          const browserLang = navigator.language || navigator.userLanguage;
          const lang = browserLang.startsWith("ru") ? "ru" : "en";

          // Сохраняем выбор, редиректим
          localStorage.setItem("preferredLang", lang);
          window.location.href = "/" + lang;
        }

        // Если уже на /ru или /en, ничего не делаем
      })();
    </script>
  </head>
  <body>
    <noscript>
      <p>
        Please enable JavaScript to be redirected automatically. <br />
        Or choose your language: <a href="/en">English</a> |
        <a href="/ru">Русский</a>
      </p>
    </noscript>
  </body>
</html>

JS (geo-block)

// For RU

(async function () {
  try {
    const res = await fetch("https://api.country.is/");
    const data = await res.json();
    const country = data.country.toLowerCase();

    const allowedCountries = ["ru"];

    if (!allowedCountries.includes(country)) {
      window.location.href = "404.html";
    }
  } catch (e) {
    window.location.href = "404.html";
  }
})();

// For EN

(async function () {
  try {
    const res = await fetch("https://api.country.is/");
    const data = await res.json();
    const country = data.country.toLowerCase();

    // Список разрешённых стран для английской версии
    const allowedCountries = ["us", "gb", "ca", "au", "de"];

    if (!allowedCountries.includes(country)) {
      // Страна не подходит — редиректим на 404
      window.location.href = "404.html";
    }
  } catch (e) {
    // если не удалось определить IP — тоже на 404
    window.location.href = "404.html";
  }
})();

// Blocked Countries

const blockedCountries = ["ru", "cn", "ir", "kp"];

if (blockedCountries.includes(country)) {
  window.location.href = "/404.html";
}

// Allowed Countries

const allowedCountries = [
  "us",
  "ca",
  "gb",
  "au",
  "nz",
  "fr",
  "de",
  "it",
  "es",
  "pt",
  "nl",
  "be",
  "ch",
  "at",
  "se",
  "no",
  "fi",
  "dk",
  "ie",
  "lu",
];

JS (geo-detect-ru)

(async function () {
  try {
    const res = await fetch("https://api.country.is/");
    const data = await res.json();
    const country = data.country.toLowerCase();

    const allowedCountries = ["ru"];

    if (!allowedCountries.includes(country)) {
      window.location.href = "404.html";
    }
  } catch (e) {
    window.location.href = "404.html";
  }
})();

JS (geo-detect-en)

(async function () {
  try {
    const res = await fetch("https://api.country.is/");
    const data = await res.json();
    const country = data.country.toLowerCase();

    const allowedCountries = [
      "us",
      "ca",
      "gb",
      "au",
      "nz",
      "fr",
      "de",
      "it",
      "es",
      "pt",
      "nl",
      "be",
      "ch",
      "at",
      "se",
      "no",
      "fi",
      "dk",
      "ie",
      "lu",
    ];

    if (blockedCountries.includes(country)) {
      window.location.href = "404.html";
    }

    if (!allowedCountries.includes(country)) {
      window.location.href = "404.html";
    }
  } catch (e) {
    window.location.href = "404.html";
  }
})();