Skip to content

Instantly share code, notes, and snippets.

@dario-valles
Last active March 28, 2022 09:15
Show Gist options
  • Save dario-valles/d680de65a0ff18b6e58c26e7be977bd3 to your computer and use it in GitHub Desktop.
Save dario-valles/d680de65a0ff18b6e58c26e7be977bd3 to your computer and use it in GitHub Desktop.
Ngix to Vercel redirects
const { readFileSync, writeFileSync, appendFileSync } = require("fs");
const ngixFile = "ngix-redirect-file.conf";
const jsonRedirectFile = "vercel.json";
ngixToVercelRedirect = (ngix) => {
const ngixParts = ngix.split(" ");
const ngixPath = ngixParts[1];
const ngixDestination = ngixParts[2];
const ngixStatusCode = ngixParts[3];
let vercelPath = ngixPath.replace("^", "").replace("$1", "").replace("$", "");
const vercelDestination = ngixDestination.replace("$1", "");
const permanent = ngixStatusCode === "permanent;";
const has = [];
if (!vercelPath || !vercelDestination || !ngixStatusCode) return undefined;
if (vercelPath.match(/\?/)) {
const searchParams = new URLSearchParams(
new URL("http://a.com" + vercelPath).search
);
searchParams.forEach((value, key) => {
if (key && value) {
has.push({
type: "query",
key,
value,
});
}
});
vercelPath = vercelPath.split("?")[0];
}
return has.length
? {
source: vercelPath,
destination: vercelDestination,
permanent,
has,
}
: {
source: vercelPath,
destination: vercelDestination,
permanent,
};
};
writeFileSync(jsonRedirectFile, "");
readFileSync(ngixFile)
.toString()
.split("\n")
.forEach((line) => {
if (line !== "" && line.indexOf("#") === -1) {
console.log(ngixToVercelRedirect(line));
// append to json file
const redirect = ngixToVercelRedirect(line);
if (redirect) {
appendFileSync(jsonRedirectFile, JSON.stringify(redirect) + ",");
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment