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

Jiew Meng picture Jiew Meng · Dec 11, 2012 · Viewed 16.1k times · Source

How can I configure nginx to redirect all URL's (not prepended with /api or some static resource eg. JS/images) to index.html? Reason is I am using HTML5 push state URL's with a single page application. Meaning content is changed whether AJAX or JS depending on the URL

My current nginx config looks like:

server {
    listen 2000;
    server_name localhost;

    location / {
        root    /labs/Projects/Nodebook/public;
        index   index.html;
    }

    location /api/ {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;

        proxy_pass http://localhost:3000/;
        proxy_redirect off;
    }
}

Answer

mattes picture mattes · Jul 2, 2014
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