Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
628 views
in Technique[技术] by (71.8m points)

angularjs - Refreshing page gives "Page not found"

I have an app where it uses a single ng-view and multiple controllers and views. If I navigate through the root, eg: www.domain.com, everything works. Except that if I hit Ctrl+R (Refresh) then it gives me the 404 eror Page not Found. eg: refreshing on this page gives me error. http://domain.com/item/1/.

But if I access the page using the hashbang then it works.eg: http://domain.com/#!/item/1/

How shall I fix this problem? My htacess is empty. And Im using chrome which support html5 hashbang.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When the browser calls http://example.com/#!/item/1/, it is calling the index page of http://example.com/, your JS then determines what content to display by analysing the hashtag.

When the browser calls http://example.com/item/1/, your server is attempting to serve the index page of http://example.com/item/1/, which it cannot find and therefore throws a 404 error.

To achieve what you want, you'll either need to:

  • Create a rewrite rule to rewrite the links to your root index page
  • adjust your JS so that it generates the hashtag instead of the URL. If you are using AngularJS then turn off html5 mode with $locationProvider.html5Mode(false);, or
  • put an index page in http://example.com/item/1/ that redirects to http://example.com/#!/item/1/ - however note that this would need to be repeated for every /prettyPath/ you crete.

Assuming you are using Apache and your index file is index.html, try adding the following to your .htaccess file to create a rewrite rule before trying either of the other two solutions.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)       /index.html/#/$1 
</IfModule>

If you are using a pure AngularJS/Ajax solution without a server side logic, change index.php to index.html (or index.htm depending on your root index filename).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...