# RFC 7239 node identifier for the peer we accepted from.  nginx has
# no built-in variable for this: an IPv6 address has to be bracketed
# and therefore quoted (RFC 7239 §6), and a peer with no address is
# "unknown" (§6.3).
map $remote_addr $paivana_forwarded_elem {
  ~^[0-9.]+$        "for=$remote_addr";
  ~^[0-9A-Fa-f:.]+$ "for=\"[$remote_addr]\"";
  default           "for=unknown";
}

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

  # server_name example.com

  location / {
    proxy_pass http://unix:/run/paivana/httpd/paivana-http.sock;
    proxy_redirect off;
    proxy_set_header Host $host;

    # paivana-httpd is started with -f (see paivana-httpd.service), so
    # it takes the client address for the access cookie from the
    # headers set here.  It believes the RIGHTMOST element of the
    # chain, which is whatever the hop it accepted from wrote -- so
    # what matters is that this server writes these headers at all.
    # $remote_addr is the peer we actually accepted; the danger is not
    # $proxy_add_x_forwarded_for (appending is safe, since our own
    # element still ends up rightmost) but leaving a header unset and
    # letting nginx forward the client's copy of it verbatim.
    #
    # If this nginx is itself behind another proxy, switch to
    # $proxy_add_x_forwarded_for, set real_ip_header /
    # set_real_ip_from for that hop, and list it in paivana's
    # TRUSTED_PROXIES so the walk may step past it.
    proxy_set_header X-Forwarded-For   $remote_addr;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-Host  $host;
    proxy_set_header X-Forwarded-Port  $server_port;

    # RFC 7239.  paivana-httpd prefers this over the X-Forwarded-*
    # headers above, which are kept for origins that only speak those.
    # Setting it is not optional: nginx forwards a client-supplied
    # Forwarded header verbatim, and since paivana prefers this header
    # over X-Forwarded-For, omitting this line would hand the client
    # the element paivana believes -- however carefully the
    # X-Forwarded-For above is set.  Behind another proxy, replace this
    # with the appending form from nginx.org's "Using the Forwarded
    # header", which validates $http_forwarded before extending it.
    proxy_set_header Forwarded "$paivana_forwarded_elem;proto=$scheme;host=$host";
  }
}
