Skip to content

Instantly share code, notes, and snippets.

@mogelbrod
Last active September 28, 2017 09:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mogelbrod/5e5c64ff943ba6909ce3bd35a57bc808 to your computer and use it in GitHub Desktop.
Save mogelbrod/5e5c64ff943ba6909ce3bd35a57bc808 to your computer and use it in GitHub Desktop.
Simple Kirby redirects plugin (compatible with https://github.com/ivinteractive/kirbycms-redirects)
<?php
// src/plugins/redirects.php
function htmlRedirect($to) {
$to = esc($to);
echo <<<EOF
<html>
<head>
<meta http-equiv="Refresh" content="0; url=$to" />
</head>
<body>
<p>Permanentely moved to <a href="$to">$to</a>.</p>
</body>
</html>
EOF;
}
$redirectsPage = page('redirects');
if (is_null($redirectsPage)) return;
kirby()->routes(array_map(function($item) {
$old = $item->old()->value();
$new = $item->new()->value();
if (page($old)) $old = '/' . ltrim(page($old)->uri(), '/'); // Domain-less URI
if (page($new)) $new = preg_replace('!^//!', '/', page($new)->url()); // Absolute URL
return [
'method' => 'GET',
'pattern' => ltrim($old, '/'),
'action' => function() use ($new) {
if (!headers_sent()) header::redirect($new);
htmlRedirect($new);
},
];
}, $redirectsPage->redirects()->toStructure()->toArray()));
# src/blueprints/redirects.yaml
title: Redirects
pages: false
fields:
redirects:
label: Redirects
type: structure
style: table
fields:
old:
label: Old URL
type: text
icon: times
new:
label: New URL
type: text
icon: check
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment