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-&gt;getRoute($event-&gt;url_query . '&amp;Itemid=' . $request-&gt;query-&gt;page_id)-&gt;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?
I think it looks good, a little verbose. Could be simplified to this

$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 need to use something like this in many locations, or you need to elaborate on what are considered bad urls a router system/class may be a better way to go.

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.