2022-02-21 08:27:50 +01:00
|
|
|
import { NextResponse } from 'next/server';
|
|
|
|
|
|
|
|
function redirectHTTPS(req) {
|
2022-03-15 16:49:42 +01:00
|
|
|
const host = req.headers.get('host');
|
2022-02-21 08:27:50 +01:00
|
|
|
if (
|
|
|
|
process.env.FORCE_SSL &&
|
2022-03-15 16:49:42 +01:00
|
|
|
process.env.NODE_ENV === 'production' &&
|
|
|
|
req.nextUrl.protocol === 'http:'
|
2022-02-21 08:27:50 +01:00
|
|
|
) {
|
2022-03-15 16:49:42 +01:00
|
|
|
return NextResponse.redirect(`https://${host}${req.nextUrl.pathname}`, 301);
|
2022-02-21 08:27:50 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function customScriptName(req) {
|
|
|
|
const scriptName = process.env.TRACKER_SCRIPT_NAME;
|
|
|
|
|
|
|
|
if (scriptName) {
|
|
|
|
const url = req.nextUrl.clone();
|
|
|
|
const { pathname } = url;
|
|
|
|
|
|
|
|
if (pathname.endsWith(`/${scriptName}.js`)) {
|
|
|
|
url.pathname = '/umami.js';
|
|
|
|
return NextResponse.rewrite(url);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function disableLogin(req) {
|
|
|
|
if (process.env.DISABLE_LOGIN && req.nextUrl.pathname.endsWith('/login')) {
|
|
|
|
return new Response('403 Forbidden', { status: 403 });
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export function middleware(req) {
|
|
|
|
const fns = [redirectHTTPS, customScriptName, disableLogin];
|
|
|
|
|
|
|
|
for (const fn of fns) {
|
|
|
|
const res = fn(req);
|
|
|
|
if (res) {
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return NextResponse.next();
|
|
|
|
}
|