Skip to content

Instantly share code, notes, and snippets.

@Disane87
Last active November 9, 2023 08:58
Show Gist options
  • Save Disane87/33c5a54b186b9dbc7c6765ac8c5e093c to your computer and use it in GitHub Desktop.
Save Disane87/33c5a54b186b9dbc7c6765ac8c5e093c to your computer and use it in GitHub Desktop.
Wordpress to ghost redirections creator

Just execute the script and paste the .htaccess content from <IfModule mod_rewrite.c> into yours.

Cheers 🎉

const fs = require('fs');
const NEW_DOMAIN = 'https://blog.disane.dev';
// Read data from the JSON file
fs.readFile('wp_ghost_export.json', 'utf8', (err, jsonString) => {
if (err) {
console.log('Error reading file:', err);
return;
}
try {
const data = JSON.parse(jsonString);
writeRedirectRules(data);
} catch (err) {
console.log('Error parsing JSON string:', err);
}
});
// Function to extract and write the redirect rules to the .htaccess file
function writeRedirectRules(data) {
const redirectRules = data.data.posts
.filter((post) => post.type === 'post' && post.status === 'published')
.map((post) => {
const date = new Date(post.created_at);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
return `RewriteRule ^${year}/${month}/${post.slug}/?$ ${NEW_DOMAIN}/${post.slug}/ [R=301,L]`;
});
const htaccessContent = `
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
# Your custom rewrite rules
${redirectRules.join('\n')}
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>`;
fs.writeFile('.htaccess', htaccessContent.trim(), (err) => {
if (err) throw err;
console.log('.htaccess file has been created successfully!');
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment