From 33d8b457c5d7984a39425c389642ec2a7e74a164 Mon Sep 17 00:00:00 2001 From: Vincent Emonet Date: Mon, 13 Sep 2021 20:29:27 +0200 Subject: [PATCH] Add an environment variable to disable basic authentication for HTTP OPTIONS to enable CORS requests. The default behavior does not change, authentication for OPTIONS is still enabled by default --- README.md | 8 ++++++++ nginx.tmpl | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/README.md b/README.md index 9e411f0..9e59ffe 100644 --- a/README.md +++ b/README.md @@ -317,6 +317,14 @@ docker run -d -p 80:80 -p 443:443 \ You'll need apache2-utils on the machine where you plan to create the htpasswd file. Follow these [instructions](http://httpd.apache.org/docs/2.2/programs/htpasswd.html) +### Enable CORS with basic authentication + +By default CORS preflight requests fails for routes requiring authentication, because all requests should only be forwarded after authentication. If you still need to enable CORS requests on a service with basic authentication you can enable `OPTIONS` requests to be passed without authentication using the `ENABLE_CORS_AUTH` environment variable: + +```console +docker run -d -p 80:80 -e ENABLE_CORS_AUTH=true -v /var/run/docker.sock:/tmp/docker.sock:ro nginxproxy/nginx-proxy +``` + ### Custom Nginx Configuration If you need to configure Nginx beyond what is possible using environment variables, you can provide custom configuration files on either a proxy-wide or per-`VIRTUAL_HOST` basis. diff --git a/nginx.tmpl b/nginx.tmpl index e79f790..d4d17a4 100644 --- a/nginx.tmpl +++ b/nginx.tmpl @@ -122,6 +122,7 @@ proxy_set_header Proxy ""; {{ $access_log := (or (and (not $.Env.DISABLE_ACCESS_LOGS) "access_log /var/log/nginx/access.log vhost;") "") }} {{ $enable_ipv6 := eq (or ($.Env.ENABLE_IPV6) "") "true" }} +{{ $enable_cors_auth := eq (or ($.Env.ENABLE_CORS_AUTH) "") "false" }} server { server_name _; # This is just an invalid value which will never trigger on a real hostname. server_tokens off; @@ -347,9 +348,16 @@ server { {{ end }} {{ if (exists (printf "/etc/nginx/htpasswd/%s" $host)) }} + {{ if $enable_cors_auth }} + limit_except OPTIONS { + auth_basic "Restricted {{ $host }}"; + auth_basic_user_file {{ (printf "/etc/nginx/htpasswd/%s" $host) }}; + } + {{ else }} auth_basic "Restricted {{ $host }}"; auth_basic_user_file {{ (printf "/etc/nginx/htpasswd/%s" $host) }}; {{ end }} + {{ end }} {{ if (exists (printf "/etc/nginx/vhost.d/%s_location" $host)) }} include {{ printf "/etc/nginx/vhost.d/%s_location" $host}}; {{ else if (exists "/etc/nginx/vhost.d/default_location") }}