# Adapted from https://github.com/gem/oq-qgis-server/blob/master/conf/qgis-server-nginx.conf
# It requires a FCGI processes spawner like spawn-fcgi or systemd (see s-server-fcgi.socket)

user nginx;
worker_processes auto;
access_log  /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

events {
    worker_connections 1024;
}

http {

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Get 'host' from `$host` unless 'X-Forwarded-Host'
    # is set by the reverse proxy.
    # 'X-Forwarded-Host' may contain also the port,
    # so it is removed from the variable
    map $http_x_forwarded_host $qgis_host {
        "~(?<h>[^:]+)" $h;
        default $host;
    }
    # Get 'PORT' from `$http_host`
    map $http_host $port {
        "~*.*:(?<p>.*)" $p;
        default $server_port;
    }
    # Get 'HTTPS' status from `$https` unless 'X-Forwarded-Proto'
    # is set by the reverse proxy and contains 'https' scheme
    map $http_x_forwarded_proto $qgis_ssl {
        "https" "on";
        default $https;
    }
    # Get 'PORT' from `$port` unless 'X-Forwarded-Port'
    # is set by the reverse proxy
    map $http_x_forwarded_port $qgis_port {
        "" $port;
        default $http_x_forwarded_port;
    }

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /usr/share/nginx/html;

        location /ows/ {
            rewrite ^/ows/(.*)$ /qgis/qgis_mapserv.fcgi?map=/var/www/ows/$1.qgs;
        }
        location /qgis/ {
            internal; # Used only by the OGC rewrite
            root /var/www/ows;
            fastcgi_pass  localhost:9993;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param QUERY_STRING    $query_string;
            # build links in GetCapabilities based on
            # the hostname exposed by the reverse proxy
            fastcgi_param  HTTPS $qgis_ssl;
            fastcgi_param  SERVER_NAME $qgis_host;
            fastcgi_param  SERVER_PORT $qgis_port;
            include fastcgi_params;
        }
        error_page 404 /404.html;
            location = /40x.html {
        }
        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

}