2
\$\begingroup\$

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?

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – mickmackusa Oct 14 at 22:16
  • \$\begingroup\$ @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. :) \$\endgroup\$ – YoKoGFX Oct 15 at 6:58
  • \$\begingroup\$ We have some pretty smart cookies over there. I recommend a cross post. \$\endgroup\$ – mickmackusa Oct 15 at 7:07
3
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.