Replace Old URLs in Joomla
There are cases where you would like to update outdated links on your site. Most administrators can use a redirection component to redirect old URLs to new ones, but old URLs may still remain inside the content itself. This is a common task in Joomla: replacing old URLs when migrating domains, moving folders, or switching from old paths to new ones. Hopefully, you don't need an extra plugin. You can do it with Tassos Code Snippets using a simple PHP snippet.
The PHP Snippet Code
This code lets you define URL replacement rules in one place and apply them to your site's final HTML output. It supports both simple text replacements and regex-based replacements, so you can handle full URL swaps and pattern-based URL updates.
use Joomla\CMS\Factory;
// Edit your URL replacement rules here.
$replacements = [
[
'search' => '#https://old-domain\\.com#',
'replace' => 'https://new-domain.com',
],
[
'search' => '#/old-section/#',
'replace' => '/new-section/',
],
];
// Do not edit below.
$app = Factory::getApplication();
$app->registerEvent('onAfterRender', function () use ($app, $replacements)
{
$document = $app->getDocument();
// Skip non-HTML responses.
if (!$document || $document->getType() !== 'html')
{
return;
}
$body = $app->getBody();
if (!is_string($body) || $body === '')
{
return;
}
$newBody = $body;
// Apply each URL replacement rule.
foreach ($replacements as $rule)
{
if (empty($rule['search']))
{
continue;
}
$newBody = preg_replace($rule['search'], $rule['replace'] ?? '', $newBody);
}
// Update output only when something changed.
if ($newBody !== $body)
{
$app->setBody($newBody);
}
});
How to add this snippet
- Install Tassos Code Snippets if it is not installed already.
- Go to your Joomla Administrator area.
- Open Components → Tassos Code Snippets.
- Click New.
- Select PHP as the snippet type.
- Select Insertion Method → Page Load.
- Paste the code above to replace old URLs.
- Optionally, open the Conditional Logic tab to restrict which pages or users the snippet runs on. Leave it empty to run it site-wide. Learn more in Using Snippet Logic.
- Publish the snippet.
Congratulations! Now, your Joomla website can dynamically replace old URLs with new ones without installing another plugin or adding unnecessary bloat. To learn more, visit the PHP Snippet works
Use Cases
- Replace old domain URLs after a site migration
- Update hardcoded links from HTTP to HTTPS
- Replace deprecated section paths with new ones
- Fix outdated documentation links in Joomla content
- Keep internal links aligned with the current site structure