Jump to content


301 Redirect Regex

  • Please log in to reply
1 reply to this topic

#1 jarvis

  • Members
  • PipPipPip
  • Advanced Member
  • 425 posts

Posted 15 March 2018 - 12:28 PM

Hi All,


I'm hoping someone can help as I'm new to regex and it's driving me mad.


I have a bunch of URLs and it basically follows the format of:



What I need to do, is redirect all the various-pages as they no longer exist. So the URL becomes:



The regex I have is as follows:

\/employer\/(.+?)\/[a-z0-9\-]+\/ \/employer\/(.+?)\/


The issue I have, I need to make company-name a variable but do an exact match


Any help is very much appreciated!


Thanks in advanced

#2 gizmola

  • Administrators
  • Advanced Member
  • 4,703 posts
  • LocationLos Angeles, CA USA

Posted 15 March 2018 - 03:23 PM

How are you planning to do the redirect? With a 404 handler?

In your site htaccess, let's assume you have this:
errordocument 404 /404.php
In your 404.php script you can start with some redirect code that parses the url to find a company-name you want to redirect for. There are a number of different ways to do this, but this one is commonly used:
$urlpath = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
// You should have just the url path, ie.   employer/company-name/foo...
Now you can simply explode to get the pieces, no need for regex at all.

Lastly you simply need to do whatever checking is appropriate to determine if you need to redirect or show a 404 page. This could be any weird url, so you'd have to flesh out the different possibilities and catch them (for example, what if $dirlist has only 1 entry? Otherwise it's pretty simple comparison logic:
$companylist = array('company1-name', 'company2-name', etc.);

$dirlist = explode('/', $urlpath);

if ($dirlist[0] == 'employer') {
    if (in_array($dirlist[1], $companylist)) {
        header('HTTP/1.1 301 Moved Permanently');
	header("Location: /employer/{$dirlist[1]}/");
// Follow this with your 404 Page markup

Edited by gizmola, 15 March 2018 - 03:55 PM.
Had a few php errors

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users