Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
script that makes an nginx config for every folder in a certain dir
const { readdirSync, statSync, writeFileSync } = require('fs')
const { join } = require('path')
// ----------------------------------------- Config
const DIR = '/home/deploy/www';
const TARGET = '/home/deploy/deployNginxConfig';
const HEADER = `
# Config generated by 'generate-nginx-config.js', do not hand-edit
index index.html;
`;
const FOOTER = `
# Config generated by 'generate-nginx-config.js', do not hand-edit
`;
const makeServerRule = name => `
server {
server_name www.${name};
return 301 $scheme://${name}$request_uri;
}
server {
server_name ${name};
root ${DIR}/${name};
location / {
try_files $uri $uri/ =404;
}
}
`;
// ----------------------------------------- Procedure
console.log();
console.log('start: generate-nginx-config');
console.log(`getting all folders inside of '${DIR}'...`);
const dirs = readdirSync(DIR).filter(f => statSync(join(DIR, f)).isDirectory());
console.log(' ' + dirs.join('\n ') + '\n');
console.log();
console.log('Generating config entries for each folder using base rule:');
console.log(makeServerRule('${name}'))
console.log();
console.log();
const rules = dirs.map(makeServerRule);
const contents = HEADER + rules.join('\n') + FOOTER;
console.log(contents);
console.log();
// Write the contents to disk
writeFileSync(TARGET, contents);
// restart nginx?
console.log('end: generate-nginx-config');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment