Files
nobat724_front/lib/getCanonicalUrl.js
T

57 lines
2.3 KiB
JavaScript

import { headers } from "next/headers";
// استراتژی canonical: محتوای همه‌ی دامنه‌های شهری از nobat724.com تغذیه می‌شود —
// پس canonical هر صفحه (روی هر دامنه‌ای) به همان مسیر روی دامنه‌ی اصلی اشاره می‌کند.
// دامنه‌ی اصلی هم self-canonical می‌گیرد.
// توجه: buildCanonicalUrl per-host است و برای JSON-LD/sitemap/robots استفاده می‌شود — به آن دست نزن.
const DEFAULT_HOST = "nobat724.com";
const MAIN_ORIGIN = "https://nobat724.com";
export function normalizeHost(rawHost) {
return (rawHost || DEFAULT_HOST).toLowerCase().replace(/^www\./, "");
}
export function buildCanonicalPath(pathname) {
let path = (pathname || "/").split("?")[0].split("#")[0];
if (!path.startsWith("/")) path = `/${path}`;
if (path.length > 1 && path.endsWith("/")) path = path.slice(0, -1);
return path;
}
export function buildCanonicalUrl(host, pathname) {
const normalizedHost = normalizeHost(host);
const hostname = normalizedHost.replace(/:\d+$/, "");
const protocol =
hostname.endsWith("localhost") || hostname === "127.0.0.1" ? "http" : "https";
return `${protocol}://${normalizedHost}${buildCanonicalPath(pathname)}`;
}
// origin هاست جاری (بدون trailing slash) — برای ساخت URLهای مطلق در JSON-LD و متادیتا
export async function getRequestOrigin() {
try {
const headersList = await headers();
return buildCanonicalUrl(headersList.get("host"), "/").replace(/\/$/, "");
} catch {
return "https://nobat724.com";
}
}
export function buildMainCanonicalUrl(pathname) {
return `${MAIN_ORIGIN}${buildCanonicalPath(pathname)}`;
}
export async function getCanonicalUrl() {
try {
const headersList = await headers();
const pathname = headersList.get("x-pathname");
// مسیرهای خارج از matcher میدل‌ور (panel/dashboard/login) این هدر را ندارند —
// آن‌ها noindex هستند و نباید canonical جعلی به ریشه بگیرند.
if (!pathname) return null;
return buildMainCanonicalUrl(pathname);
} catch (error) {
console.error("Error generating canonical URL:", error);
return null;
}
}