How to implement a 301 redirect in the same way SO does it.
(Assumes there's a table called questions
with columns id
and title
)
(Note: there's likely also heavy use of Memcached by SO rather than DB access for every page view, but that's another topic.)
For the URL:
http://stackoverflow.com/questions/824349
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.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");
}