Jump to content

Redirect old urls using head.inc and API


woop
 Share

Recommended Posts

Hi! I'm no php expert but I thought I should share my way of redirecting URLs from my old site setup. I'm going to use Drupal urls in this example, but should work for any url. I can't guarantee this is the best way of doing it, so please feel free to correct me if you have feedback regarding security, speed or similar.

Step 1:

Make sure that each page in PW has some kind of connection to its previous URL so it can recognize when a redirect needs to be done. I'm going to use the node id:s and taxonomy id:s that my pages had when they were located in Drupal. I've made sure to save them all into each processwire page in a field called "drupal_id". Maybe you could just save the old URL in a field when migrating and use that, as an alternative.

Step 2:

Open head.inc and add this to the very top:

$thisurl = $sanitizer->url("http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");

// Check if the URL reminds you of the old url scheme
if (preg_match("/com\/\?q=/", $thisurl)){
	// if it looks like a node url
	if (preg_match("/\?q=node\/[0-9]*/", $thisurl, $nodeslug)){
		$oldnid = preg_replace("/\?q=node\//", "", $nodeslug[0]);
		if ($match = $pages->get("drupal_id={$oldnid}")){
			$session->redirect($match->httpUrl);
		} else {
			$session->redirect($config->urls->root); 
		}
	// If it's a taxonomy url
	} elseif (preg_match("/\?q=taxonomy\/term\/[0-9]*/", $thisurl, $taxonomyslug)) {
		$oldtid = preg_replace("/\?q=taxonomy\/term\//", "", $taxonomyslug[0]);
		if ($match = $pages->get("drupal_id={$oldtid}")){
			$session->redirect($match->httpUrl);
		} else {
			$session->redirect($config->urls->root);
		}
	} else {
		$session->redirect($config->urls->root); 
	}
	
}

Regex is used to find URL schemes and extract drupal nids and tids from the url. These are then looked up using the api, only to return the new url. Each time the url redirect fails, it might be suitable presenting a warning to the user. I've added something like $session->message("This URL seems to have changed. Please use the search if you didn't find what you were looking for") on the line before redirect (not part of the code example above, for simplicity's sake).

Hope this can be useful for someone else, too. And again, feel free to leave feedback! I'm here to learn, too :)

  • Like 5
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...