Nginx + node.js single page app, sending /index.html and proxying together

httpnginxnode.js

I've got a Nginx running, with Node.js on port 3000.

    location / {
        root   /path/to/my/site;
        index  index.html index.htm;
        try_files $uri $uri/ @node;
    }

    location @node {

        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://127.0.0.1:3000;
        proxy_redirect off;

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

    }

this works perfectly, getting node content when the url is not a file. (so this loads socket.io/socket.io.js fine).

Now i want all pages to redirect to my index.html in the root. So when a users refreshes //domain/with/extra/path; i want to ship the root //domain/index.html.

i would need a rewrite for this, but that would destroy my checking for node files. So i need something that only redirects the GET /(url)/ to my root /index.html, not GET files.

Best Answer

Adding this to your location / should cause any request with a trailing slash to load the index page:

rewrite ^/.*/$ / last;

Or if you want to send their browser a redirect response so their address bar points to the new location, swap last for permanent (or redirect if you'd prefer a 302 over a 301).