How to implement 301 redirection in the same way as SO does.
(It is assumed that there is a table called questions with the id and title columns)
(Note. It is probably also very important to use Memcached by SO, not DB access for each page view, but this other section.)
For URL:
http:
Your .htaccess will rewrite URLs in the format questions.php?id=123&sef=abc-def :
RewriteRule ^/questions/([0-9]+)/?([\w\-]*)$ /question.php?id=$1&sef=$2
Your question is .PHP script
<?php // Get the posted id (as int to prevent sql injection) $id = isset($_GET['id']) ? (int) $_GET['id'] : 0; // Get the posted search-engine-friendly title string (if any) $sef = isset($_GET['id']) ? $_GET['sef'] : ''; // Connect to the database mysqli_connect(...); // Get the question with the provided id $result = mysqli_query("SELECT * FROM questions WHERE id = {$id}"); // If a question was found if ($row = mysqli_fetch_assoc($result)) { // Find the SEF title for the question (lowercase, replacing // non-word characters with hyphens) $sef_title = strtolower(preg_replace('/[^\w]+/', '-', $row['title']); // If the generated SEF title is different than the provided one, if ($sef_title !== $sef) { // 301 the user to the proper SEF URL header("HTTP/1.1 301 Moved Permanently"); header("Location: http://stackoverflow.com/question/{$id}/{$sef_title}"); } } else { // If no question found, 302 the user to your 404 page header("Location: http://stackoverflow.com/404.php"); }
source share