antivinegar antivinegar - 3 months ago 10
Apache Configuration Question

Redirection by querying database value like stackoverflow.com URLs

So I use the following htaccess code to redirect the URLs to clean looking URLs but, now what I need to happen is to have the original URLs to redirect to the new clean URLS.

Example

Original URL:

example.com/search/store_info.php?store=113&dentist=Dr.%20John%20Doe


Clean URL:

example.com/search/113/dr-john-doe


What I need is the "ORIGINAL URL" to redirect to the "CLEAN URL". Reason why I need this to happen is that both URLs are showing up in Google searches.

I only want the clean URL to show up and anytime the original URL is used it should automatically redirect to the clean URL. It currently doesn't do that.

Here is my htaccess file.

ErrorDocument 404 default

<IfModule mod_rewrite.c>
Options -MultiViews
RewriteEngine On
RewriteBase /search/

RewriteCond %{QUERY_STRING} .
RewriteCond %{THE_REQUEST} /store_info\.php\?store=([a-z0-9]+)&dentist=([^\s&]+) [NC]
RewriteRule ^ %1/%2/? [L,NE,R=301]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_URI} \.(?:jpe?g|gif|bmp|png|ico|tiff|css|js)$ [NC]
RewriteRule ^ - [L]

RewriteRule ^([a-z0-9]+)/([^\s.]*)[.\s]+(.*)$ $1/$2-$3 [NC,DPI,E=DONE:1]

RewriteCond %{ENV:DONE} =1
RewriteRule ^([0-9a-z]+)/([^\s.]+)$ $1/$2 [R=301,NE,L]

RewriteRule ^([a-z0-9]+)/([a-z0-9-]+)/?$ store_info.php?store=$1&dentist=$2 [QSA,L,NC]

</IfModule>


I've read about RedirectMatch however I don't know where to implement it into my htaccess file.

Answer

Inside your store_info.php have code like this:

<?php
$store = $_GET['store'];

if (empty($store)) {
   header("HTTP/1.1 404 Not Found");
   exit;
}

$dentist = $_GET['dentist']);

// pull dentist from DB by store id. Create this function in PHP and
// query your database
$dentistFromDB = preg_replace('/[\h.]+/', '-', $row['businessName']);

// DB returns an empty or no value
if (empty($dentistFromDB)) {
   header("HTTP/1.1 404 Not Found");
   exit;
}

// DB returned value doesn't match the value in URL
if ($dentistFromDB != $dentist) {
   // redirect with 301 to correct /<store>/<dentist> page
   header ('HTTP/1.1 301 Moved Permanently');
   header('Location: /' . $store . '/' . $dentistFromDB);
   exit;
}

// rest of the PHP code should come now

?>
Comments