Redirect WordPress in Header

WordPress Header Redirect

The redirection plugin built for WordPress is a fantastic means of organizing and managing redirects. I use it on this site and have organized my groups of redirects for updated posts, affiliate links, downloads, etc.

However, I ran into a unique problem where I have a reverse proxy set up for a client where WordPress is running at a path… but not the root of the site. The primary site is running on IIS in Azure. IIS can manage redirects just as any web server can, but the problem is that this client would need to put redirect management into their development process – and they’re busy already.

At issue is that a typical .htaccess style redirect isn’t a possibility… we have to actually write the redirects in PHP. As a solution, we route the requests to WordPress to identify if there are any redirects on old paths.

Within the header.php file of our child theme, we have a function:

function my_redirect ($oldlink, $newlink, $redirecttype = 301) {
	$olduri = $_SERVER['REQUEST_URI'];
	if(strpos($olduri, $oldlink) !== false) {
		$newuri = str_replace($oldlink, $newlink, $olduri);
		wp_redirect( $newuri, $redirecttype );

We didn’t bother putting the function in functions.php simply because it would only be impacting the header file. Then, within the header.php file, we simply have a list of all the redirects:

my_redirect('lesson_plans', 'lesson-plan');
my_redirect('resources/lesson-plans/26351', 'lesson-plan/tints-and-shades');
my_redirect('about/about', 'about/company/');

With that function, you can also specify what type of redirect you’d like to set the header request to, we’ve just defaulted it to a 301 redirect so that the search engines will honor it.