如何以与 SO 相同的方式实现 301 重定向。
(假设有一个名为questions
列的表id
和title
)
(注意:SO 也可能大量使用 Memcached,而不是对每个页面视图进行数据库访问,但这是另一个主题。)
对于网址:
http://stackoverflow.com/questions/824349
您的 .htaccess 将以以下格式重写 URL questions.php?id=123&sef=abc-def
:
RewriteRule ^/questions/([0-9]+)/?([\w\-]*)$ /question.php?id=$1&sef=$2
你的 question.php 脚本
<?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");
}