# Define API rate limitation
limit_req_zone $binary_remote_addr zone=cycloAPI:10m rate=1r/s;# UWSGI proxy pass

# Define the server to use upstream, here we assume we serve Cyclassist using
# UWSGI.
upstream _cyclassist {
    server unix:/run/uwsgi/app/cyclassist/socket;
}

# Expires map, to ensure correct caching of the assets.
map $sent_http_content_type $expires {
    default                    off;
    text/html                  epoch;
    text/css                   max;
    application/javascript     max;
    ~image/                    max;
}

server {
    listen 443 ssl http2;
    server_name SERVER_NAME;
    root /var/www/cyclassist/dist;

    access_log  /var/log/nginx/cyclo-access.log combined;
    error_log   /var/log/nginx/cyclo-error.log warn;

    ssl                  on;
    ssl_certificate      /etc/letsencrypt/live/cyclo.phyks.me/fullchain.pem;
    ssl_certificate_key  /etc/letsencrypt/live/cyclo.phyks.me/privkey.pem;
    # Tweak the SSL ciphers and so on, see https://wiki.mozilla.org/Security/Server_Side_TLS.

    # Enable GZIP
    gzip on;
    gzip_disable "msie6";
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_min_length 256;
    gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript application/vnd.ms-fontobject application/x-font-ttf font/opentype image/svg+xml image/x-icon;

    # Cache control
    expires $expires;
    location ~* \.(?:woff2?|eot|ttf|otf?g) {
        expires max;  # Max caching for font files
    }

    # No caching for the service worker file
    location = /sw.js {
        add_header Last-Modified $date_gmt;
        add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        if_modified_since off;
        expires off;
        etag off;
    }

    # Proxy pass the API calls to the server part
    location /api {
        limit_req zone=cycloAPI burst=3 nodelay; # Add rate-limiting on top of the API
        include uwsgi_params;
        uwsgi_pass _cyclassist;
    }
}


server {
    listen      80;
    server_name SERVER_NAME;

    root /dev/null;

    include /etc/nginx/snippets/common_vhost.conf;

    return 301 https://$server_name$request_uri;  # Redirect to HTTPS
}
