upstream rails-server {
    server 127.0.0.1:3000 fail_timeout=0;
}

upstream phoenix-server {
    server 127.0.0.1:4000 fail_timeout=0;
}

proxy_cache_path /cache levels=1:2 keys_zone=png_cache:10m max_size=10g
                 inactive=14d use_temp_path=off;

map $http_x_forwarded_proto $real_scheme {
    default $http_x_forwarded_proto;
    ''      $scheme;
}

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    server_name _;

    root /app/public;

    client_max_body_size 16m;

    location ~ ^/(phoenix/|css/|js/|images/|fonts/|docs/?|api/asciicasts|connect/) {
        try_files /maintenance.html $uri/index.html $uri.html $uri @phoenix;
    }

    location ~ ^/a/[^.]+\.png$ {
        proxy_cache png_cache;
        proxy_cache_revalidate on;
        proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
        proxy_cache_lock on;
        proxy_cache_key $uri;
        proxy_ignore_headers Set-Cookie;

        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $real_scheme;
        proxy_set_header Host $http_host;
        proxy_pass http://phoenix-server;
        proxy_redirect off;
    }

    location ~ ^/a/[^.]+\.(json|gif)$ {
        try_files $uri $uri/index.html $uri.html @phoenix;
    }

    location / {
        try_files $uri $uri/index.html $uri.html @rails;
    }

    location ~ ^/assets/ {
        expires 1y;
        add_header Cache-Control public;

        add_header ETag "";
        break;
    }

    location @rails {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $real_scheme;
        proxy_set_header Host $http_host;
        proxy_pass http://rails-server;
        proxy_redirect off;
        error_page 500 502 504 /500.html; # Rails error pages
    }

    location @phoenix {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $real_scheme;
        proxy_set_header Host $http_host;
        proxy_pass http://phoenix-server;
        proxy_redirect off;
    }
}
