Configuring nginx for single page website with HTML5 push state URL's

早过忘川 提交于 2019-11-29 23:12:44
location / {
  try_files $uri /index.html;
}

This will check if the requested file exists and return it. If the file doesn't exist, it will return index.html.

http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files

mattes answer is almost a solution, however it won't give 404 for missing files (e.g. favicon.icon) as aschepis pointed out.

Nginx will pick the first location that matches. So we can first match for files (which will give 404 if the file does not exist). And after put a location which defaults to index.html for all urls.

    location /.+\..+ { # files (assuming they always have a dot)
        # use eg alias to serve some files here
    }

    location / { # url routed by client, client gives 404 for bad urls
        try_files $uri /index.html;
    }

You need to add to your nginx config file:

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

Then say you're using Backbone.js just make sure you re-route any non-defined route to a 404 page:

  routes: {
    // Other routes
    "*path"  : "notFound"
  },

  notFound: function(path) {
    // Load 404 template, probably of a cute animal.
  }

Source: http://readystate4.com/2012/05/17/nginx-and-apache-rewrite-to-support-html5-pushstate/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!