Mobile app version of vmapp.org
Login or Join
Yeniel560

: How to perform a 301 redirect with .htaccess and PHP The website I am referencing in my question is http://www.bgmenus.com. I have successfully created clean urls like this for my listings:

@Yeniel560

Posted in: #Htaccess #Php #Seo

The website I am referencing in my question is www.bgmenus.com.

I have successfully created clean urls like this for my listings: bgmenus.com/five-guys/341
I rewrote those using this: RewriteRule /([^/.]+)/?$ /restaurants.php?id= [L,NC,QSA]

The issue is the old URLs still exist and work: bgmenus.com/restaurants.php?id=341
My question is how can I 301 the /restaurants.php?id=123 version of the URL back to the clean version so there aren't any duplicates.

Thanks for your help.

10.04% popularity Vote Up Vote Down


Login to follow query

More posts by @Yeniel560

3 Comments

Sorted by latest first Latest Oldest Best

 

@Megan663

.htaccess has no way of mapping restaurants.php?id=123 to /five-guys/341; it cannot pull the five guys slug from the database. You need to do this by coding. Here is a rough outline:

// $row variable comes from database
// it might look like
// array("id" => 123, "slug" => "five-guys", "name" => "Five Guys");

$requestedURL = $_SERVER['REQUEST_URI'];
$preferredURL = '/' . $row['slug'] . '/' . $row['id'];

if ($requestedURL !== $preferredURL) {
header ($_SERVER['SERVER_PROTOCOL'] . ' 301 Moved Permanently');
header ('Location: ' . $_SERVER['HTTP_HOST'] . $preferredURL);
die();
}


Depending on your server, the original URL might be logged in another server variable. If you are not sure, so a var_dump($_SERVER) to locate the variable that contains the before-rewriting URL.

10% popularity Vote Up Vote Down


 

@Barnes591

You cannot get restaurant name from URL since you only have id.
Just based on id you can use this rule above your existing rule:

RewriteCond %{THE_REQUEST} s/+restaurants.php?id=([^s&]+) [NC]
RewriteRule ^ /restaurant/%1? [R=302,L]


This redirects /restaurants.php?id=123 to /restaurant/123

10% popularity Vote Up Vote Down


 

@Martha676

You could check the $_SERVER['REQUEST_URI'] on the php script restaurants.php if the request url is the correct. For example:

if ($_SERVER['REQUEST_URI'] !== '/' . $name . '/' . $id)
{
header ('HTTP/1.1 301 Moved Permanently');
header ('Location: www.bgmenus.com/' . $name . '/' . $id);
die();
}


Where $name is the restaurant name [five-guys] and $id is the restaurant id [341]

When the hit is from bgmenus.com/five-guys/341 the if statement would be false
If someones direct hits /restaurants.php?id=123, the if will be true and the user will be redirected to the new seo friendly url

10% popularity Vote Up Vote Down


Back to top | Use Dark Theme