Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { NextRequest, NextResponse } from 'next/server';
const PUBLIC_FILE = /\.(.*)$/;
const supportedLocales = ['en', 'ru', 'hy'];
const defaultLocale = 'en';
const ARTICLE_PATH = /^(?:\/(?:en|ru|hy))?\/articles\/([^/]+)\/?$/;
const ARTICLE_SLUG = /^[A-Za-z0-9_-]+$/;

export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
Expand Down Expand Up @@ -30,6 +32,19 @@ export async function middleware(request: NextRequest) {
return NextResponse.redirect(new URL(`/${matchedLocale}`, request.url));
}

// Crawlers follow article URLs with a stray encoded tail (`slug%29`,
// `slug%252529`, ...) that grows by one encoding per hop. Article slugs are
// [A-Za-z0-9_-] only, so anything after that prefix is cut off with a 301.
const article = ARTICLE_PATH.exec(pathname);
if (article && !ARTICLE_SLUG.test(article[1])) {
const slug = /^[A-Za-z0-9_-]+/.exec(article[1])?.[0];
if (slug) {
const url = request.nextUrl.clone();
url.pathname = `/articles/${slug}`;
return NextResponse.redirect(url, 301);
}
}

return NextResponse.next();
}

Expand Down
6 changes: 4 additions & 2 deletions src/pages/articles/[page].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,10 @@ export const getStaticProps: GetStaticProps = async ({
const articles: TArticle[] = await getArticles(locale === 'ru' ? 'ru' : 'en');
const article = page && getCurrentArticle(articles, page);

if (!article) {
return { notFound: true };
// getCurrentArticle returns {} on a miss, so an unknown slug must be caught
// by its keys: rendering it as a 200 page let crawlers loop on junk URLs.
if (!article || !Object.keys(article).length) {
return { notFound: true, revalidate: 10 };
}

const recommendedArticles = getRecommendedArticles(articles, page);
Expand Down
Loading