nginx: send all requests to a single html page

JavascriptNginxHistory

Javascript Problem Overview


Using nginx, I want to preserve the url, but actually load the same page no matter what. I will use the url with History.getState() to route the requests in my javascript app. It seems like it should be a simple thing to do?

location / {
    rewrite (.*) base.html break;
}

works, but redirects the url? I still need the url, I just want to always use the same page.

Javascript Solutions


Solution 1 - Javascript

I think this will do it for you:

location / {
    try_files /base.html =404;
}

Solution 2 - Javascript

Using just try_files didn't work for me - it caused a rewrite or internal redirection cycle error in my logs.

The Nginx docs had some additional details:

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

So I ended up using the following:

root /var/www/mysite;

location / {
    try_files $uri /base.html;
}

location = /base.html {
    expires 30s;
}

Solution 3 - Javascript

Your original rewrite should almost work. I'm not sure why it would be redirecting, but I think what you really want is just

rewrite ^ /base.html break;

You should be able to put that in a location or directly in the server.

Solution 4 - Javascript

This worked for me:

location / {
    alias /path/to/my/indexfile/;
    try_files $uri /index.html;
}

This allowed me to create a catch-all URL for a javascript single-page app. All static files like css, fonts, and javascript built by npm run build will be found if they are in the same directory as index.html.

If the static files were in another directory, for some reason, you'd also need something like:

# Static pages generated by "npm run build"
location ~ ^/css/|^/fonts/|^/semantic/|^/static/ {
    alias /path/to/my/staticfiles/;
}

Solution 5 - Javascript

This worked for me:

location / {
	try_files $uri $uri/ /base.html;
}

Solution 6 - Javascript

The correct way would be:

location / {
    rewrite (.*) base.html last;
}

Using last will make nginx find a new suitable location block according to the result of rewriting.

try_files is also a perfectly valid approach to this problem.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionprismofeverythingView Question on Stackoverflow
Solution 1 - JavascriptAlex HowanskyView Answer on Stackoverflow
Solution 2 - JavascriptKevan StannardView Answer on Stackoverflow
Solution 3 - JavascriptkolbyjackView Answer on Stackoverflow
Solution 4 - JavascriptMark ChackerianView Answer on Stackoverflow
Solution 5 - JavascriptAbhishekView Answer on Stackoverflow
Solution 6 - JavascriptEtherealoneView Answer on Stackoverflow