Mod_ReWrite / ReWriteMap a URL using a database lookup script

馋奶兔 提交于 2019-12-01 14:57:08

Your query:

SELECT
  ID
FROM
  thetable
WHERE
  ProductID=?

From there just echo the value of ID and a newline, and flush stdout.

Rewrite rules:

RewriteMap dbfixup prg:dbfixup.script
RewriteCond %{QUERY_STRING} ProductID=(\d+)
RewriteRule Product.asp Products.php?ID=${dbfixup:%1}

You should have a different get variable name for the new ID. That way in your new program you will know whether to match the product using the old ID or the new one.

$old = isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0 ? $_GET['id'] : 0;
$new = isset($_GET['new']) && is_numeric($_GET['new']) && $_GET['new'] > 0 ? $_GET['new'] : 0;
if ($old + $new > 0) {
    $query = 'SELECT * FROM `ProductDetails` WHERE '.($old > 0 ? '`OrigPrdID`='.$old : '`PrdDetID`='.$new).' LIMIT 1;';
    ...

After finding out RewriteMap is disabled by my host, I've reached my own solution simply using mod_rewrite and 2x 301 redirects.

.htaccess file

RewriteEngine on
RewriteRule ^Product(.*)\.asp SEO_Redirect.php [NC,R=301]

SEO_Redirect.php file

$ID = $_GET['ID'];

$query_rsNewID = "SELECT NewProductID FROM Products WHERE OldProductID = '$ID'";
$rsNewID = mysql_query($query_rsNewID, $Database);
$row_rsNewID = mysql_fetch_assoc($rsNewID);

header ('HTTP/1.1 301 Moved Permanently');
header ('Location: Product.php?ID='.$row_rsNewID['NewProductID']);

Note, this is a simplified excerpt of each file, and would not be secure against SQL injection.

Hopefully Google and alike will accept getting 2x 301 redirects without problems.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!