Hosting an ember-cli app with nginx

 

I've recently deployed my ember app on a private server. My first naive approach was something like: 

server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
root /home/ivo/myapp;
index index.html;

location / { # First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
# Uncomment to enable naxsi on this location
# include /etc/nginx/naxsi.rules
}
}

 

Seems to work well - / serves the index.html and all other assets/resources are also served nicely. It indeed did work perfectly, unless you use the 'location api' for your URL's, e.g.

 

http://host/item/123/edit

and reload the current page (this happens quickly on a tablet). The browser will send the URL verbatim to the server since there's no ember at that point to handle it locally anymore which will result in a 404.


The trick is to have the server try to serve a resource locally (e.g. javascript, stylesheet, font, robots.txt) or else default/redirect (internally) to /index.html. This can be done with the following setup:

 

server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on; root /home/ivo/myapp;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}

 

The trick is to have /index.html as the last option to try_files. Not =404 and not / because those will cause external redirects. As far as I know this is the only way to internally redirect which means the URL in the browser will remain in tact and allow ember to handle the URL locally. In other words, opening http://host/item/123/edit will open that actual route directly!

 

However, this does disable 404 handling. If some resource is missing it will automatically get the index.html contents as result which may get confusing. The only solution I can think of is to mixing the above but explicitly map  assets, fonts, robots.txt and crossdomain.xml (and whatever may get added). But for now, for a sort-of-production-setup, this works fine.

Last updated July 28, 2015, 2:20 p.m. | deploy ember ember-cli emberjs nginx
comments powered by Disqus