How to cope with refreshing page with JS History API pushState How to cope with refreshing page with JS History API pushState javascript javascript

How to cope with refreshing page with JS History API pushState


You shouldn't use pushState to push invalid URLs at all. It's meant to be used in cases where the site works both with and without AJAX - i.e. you push the URL which would result in the same output without AJAX when creating this output with AJAX.

If you want only virtual URLs (like in the pre-pushState era), keep using the hash tag.


This is a somewhat old question, but it was one of the top google results. In the pursuit of being helpful, here is my solution.

You can use Apache's Mod_Rewrite to rewrite the url to a central location.For example:example.com/p2 gets its page content from example.com/index.php?page=p2You can keep your current implementation of the History API and AJAX to get the content and include the following in your .htaccess

<ifModule mod_rewrite.c>  RewriteEngine On  RewriteRule ^([^/\.]+)/?$ index.php?page=$1&full=1 [L]</ifModule>

In your index.php:

<?php  if(isset($_GET['full']) {    //Generate the full page here  }else{    //Generate just the content for AJAX  }?>

This Page is a good primer on using mod_rewrite to redirect an entire website. (Comments 11 & 13 have useful additions as well)


I had to redirect 404 errors to the sites homepage (the one that loads the AJAX requests), and then get the last component of the URL, and run the javascript function that loads the page using an AJAX request. Not a great solution but it seems to work well.