堆栈溢出如何替换状态?

时间:2013-06-08 18:58:05

标签: javascript

我是mac用户,从不使用IE。但是昨天上班时我进入堆栈溢出并使用IE 9将其输入浏览器...

http://stackoverflow.com/questions/824349

他们将URL替换为此而不刷新页面......

http://stackoverflow.com/questions/824349/modify-the-url-without-reloading-the-page

我无法相信我所看到的。堆栈溢出如何能够利用模拟历史API在不支持它的浏览器上替换状态的任何想法?

3 个答案:

答案 0 :(得分:9)

他们实际上通过301重定向重定向用户。看看标题:

GET /questions/824349 HTTP/1.1
Host: stackoverflow.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0
[...]

HTTP/1.1 301 Moved Permanently
Cache-Control: public, max-age=60
Content-Type: text/html
Expires: Sat, 08 Jun 2013 19:00:05 GMT
Last-Modified: Sat, 08 Jun 2013 18:59:05 GMT
Location: /questions/824349/modify-the-url-without-reloading-the-page
Vary: *
X-Frame-Options: SAMEORIGIN
Date: Sat, 08 Jun 2013 18:59:05 GMT
Content-Length: 0

答案 1 :(得分:3)

这是301 Moved Permanently重定向,即它已完成服务器端。您没有看到刷新,因为浏览器没有打开第一个URL,它会立即重定向到第二个URL。

这是chrome控制台上的结果。

enter image description here

答案 2 :(得分:2)

如何以与SO相同的方式实现301重定向。

(假设有一个名为questions的表格,列idtitle

(注意:对于每个页面视图,可能还会通过SO大量使用Memcached而不是DB访问,但这是另一个主题。)

对于网址:

http://stackoverflow.com/questions/824349

您的.htaccess将以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");
}