# PHP code for blacklisting and rewriting/redirecting URLs

We faced an issue where URLs had a wrong "subfolder" in its URL, so e.g.

example.com/match1/randomgenerated


should have been

example.com/rewritewiththis/randomgenerated


We currently use this code for redirecting URLs that (maybe it could be that it only starts at urls that are "bad"):

$oldurl = JUri::getInstance();$newurl = str_replace(['match1','match2','match3'], 'rewritewiththis', $oldurl);$bad_urls = array('match1','match2','match3');

foreach($bad_urls as$bad_url){
if(strpos($oldurl,$bad_url) !== false) {
exit(header("Location: $newurl", true, 301)); } }  We use the $newurl also for things like this (this rewrites the generated URLs to use a correct URL and prevent duplicate content):

$oldurl =$this->getRoute($event->url_query . '&Itemid=' .$request->query->page_id)->toString();
$data['url'] = str_replace('match1', 'rewritewiththis',$oldurl);


Are there better options to do this are are is this already a good way to solve this issue?

• If this is a Joomla script, you might like to ask at Joomla Stack Exchange -- where folks with intimate knowledge about the CMS can tell you about pre-scripted functionalities and best practices within the CMS. – mickmackusa Oct 14 at 22:16
• @mickmackusa yes, this was about Joomla. The issue here is that we don't have such a deep knowledge of the component, as we didn't program it fully. The URL generation is one of this, that we didn't change. But thanks for the link to the Joomla Stack Exchange. :) – YoKoGFX Oct 15 at 6:58
• We have some pretty smart cookies over there. I recommend a cross post. – mickmackusa Oct 15 at 7:07

$oldurl = JUri::getInstance();$bad_urls = ['match1','match2','match3'];
$newurl = str_replace($bad_urls, 'rewritewiththis', $oldurl); if(in_array($oldurl, $bad_urls)) exit(header("Location:$newurl", true, 301));

If you're asking if there's a different way to re-route without using header() I don't think there is. Any router system I have seen uses header() to re-route, no matter how much code surrounds and abstracts them.