Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
    }
}
like image 912
Jiew Meng Avatar asked Dec 11 '12 02:12

Jiew Meng


2 Answers

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

like image 143
mattes Avatar answered Oct 03 '22 07:10

mattes


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;
    }
like image 33
j-a Avatar answered Oct 03 '22 07:10

j-a