antivinegar antivinegar - 1 year ago 124
Apache Configuration Question

htaccess Rewrite Rule for 301 RedirectMatch

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.


Original URL:

Clean URL:

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]


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

Answer Source

Inside your store_info.php have code like this:

$store = $_GET['store'];

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

$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");

// 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);

// rest of the PHP code should come now

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download