How does stack overflow replace state?

I am a Mac user and never use IE. But yesterday at work, I went for a stack overflow and typed it in a browser using IE 9 ...

http://stackoverflow.com/questions/824349 

And they replaced the url with this without refreshing the page ...

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

I could not believe what I saw. Any ideas on how a stack overflow can use functionality that mimics a history API API condition in a browser that doesn't support it?

+4
source share
3 answers

They actually redirect the user with a 301 redirect. Look at the headlines:

 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 
+9
source

This is a 301 Moved Permanently Forwarding, i.e. made on the server side. You do not see the update, because the browser does not open the first URL, it redirects immediately to the second.

Here the result on the console is chrome.

enter image description here

+3
source

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://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 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"); } 
+2
source

Source: https://habr.com/ru/post/1485208/


All Articles