简体   繁体   中英

HTML5 history pushState link back

After seeing another post earlier today on the HTML5 History API and reading the tutorial at Mozilla , I've been able to implement a basic working demo for using this API to allow URL "rewriting" without reloading the page and without using a hash.

My question is: Let's say you have a user who comes to a page, clicks on one of these links that uses the History API to write the new URL. Then the user bookmarks the page. Now I'm assuming it will now bookmark the rewritten URL. So when the user comes back in a couple of days or something and tries to go to the bookmarked page, won't it return a 404? And so how can you implement a way for it to resolve somehow?

This is assuming that the URL I rewrite points to a non-existent location.

I just encountered this issue today and wrote an entry about it on my blog : When using HTML5 pushstate if a user copies or bookmarks a deep link and visits it again, then that will be a direct server hit which will 404.

Even a js pushstate library won't help you here as this is a direct server call being requested before the page and any JS even loads.

The easiest solution is to add a rewrite rule to your Nginx or Apache server to internally rewrite all calls to the same index.html page. The browser thinks it's being served a unique page when it's actually the same page:

Apache (in your vhost if you're using one):

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
 </IfModule>

Nginx

 rewrite ^(.+)$ /index.html last; 

You would still, of course, add some JS logic to display the correct content. In my case I'm using Backbone routes which handles this easily.

I know this is old but you are completely misusing pushstate. Say you have a page to see artists, lets call it artists.php. And if they click on one, they can see an artists bio. So you have "another" page, artists.php?artist=journey

Now, say you decide you will load the bio asynchronously in a modal window, so you add an ajax trigger to disable the layout and just get the content (artists.php?artist=journey&ajax=true). You could "push" artists.php?artist=journey to the history, and make it so that if that page is loaded, it loads your artists page with journey preloaded in a modal window.

That way you can use it to make bookmarking different states of your page possible - not just have pretty URLs when they click somewhere.

This should be done by server side scripts. The server should parse URL and make the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM