diff --git a/.github/workflows/build-publish.yml b/.github/workflows/build-publish.yml index 6aeb9f540..b714de7a8 100644 --- a/.github/workflows/build-publish.yml +++ b/.github/workflows/build-publish.yml @@ -81,7 +81,7 @@ jobs: - name: Build and push the image id: docker_build - uses: docker/build-push-action@v5 + uses: docker/build-push-action@v6 with: context: . file: Dockerfile.${{ matrix.base }} diff --git a/Dockerfile.alpine b/Dockerfile.alpine index e4ec6d6c4..c602cdfc5 100644 --- a/Dockerfile.alpine +++ b/Dockerfile.alpine @@ -1,9 +1,9 @@ -FROM nginxproxy/docker-gen:0.11.1 AS docker-gen +FROM docker.io/nginxproxy/docker-gen:0.14.3 AS docker-gen -FROM nginxproxy/forego:0.18.1 AS forego +FROM docker.io/nginxproxy/forego:0.18.2 AS forego # Build the final image -FROM nginx:1.25.3-alpine +FROM docker.io/library/nginx:1.27.2-alpine ARG NGINX_PROXY_VERSION # Add DOCKER_GEN_VERSION environment variable because @@ -17,8 +17,13 @@ ENV NGINX_PROXY_VERSION=${NGINX_PROXY_VERSION} \ RUN apk add --no-cache --virtual .run-deps bash openssl # Configure Nginx -RUN sed -i 's/worker_connections 1024/worker_connections 10240/' /etc/nginx/nginx.conf \ - && mkdir -p '/etc/nginx/dhparam' +RUN echo -e "\ninclude /etc/nginx/toplevel.conf.d/*.conf;" >> /etc/nginx/nginx.conf \ + && sed -i 's/worker_connections.*;$/worker_connections 10240;/' /etc/nginx/nginx.conf \ + && sed -i -e '/^\}$/{s//\}\nworker_rlimit_nofile 20480;/;:a' -e '$!N;$!ba' -e '}' /etc/nginx/nginx.conf \ + && mkdir -p '/etc/nginx/toplevel.conf.d' \ + && mkdir -p '/etc/nginx/dhparam' \ + && mkdir -p '/etc/nginx/certs' \ + && mkdir -p '/usr/share/nginx/html/errors' # Install Forego + docker-gen COPY --from=forego /usr/local/bin/forego /usr/local/bin/forego diff --git a/Dockerfile.debian b/Dockerfile.debian index 2d767fe80..ec63da850 100644 --- a/Dockerfile.debian +++ b/Dockerfile.debian @@ -1,9 +1,9 @@ -FROM nginxproxy/docker-gen:0.11.1-debian AS docker-gen +FROM docker.io/nginxproxy/docker-gen:0.14.3-debian AS docker-gen -FROM nginxproxy/forego:0.18.1-debian AS forego +FROM docker.io/nginxproxy/forego:0.18.2-debian AS forego # Build the final image -FROM nginx:1.25.3 +FROM docker.io/library/nginx:1.27.2 ARG NGINX_PROXY_VERSION # Add DOCKER_GEN_VERSION environment variable because @@ -14,8 +14,13 @@ ENV NGINX_PROXY_VERSION=${NGINX_PROXY_VERSION} \ DOCKER_HOST=unix:///tmp/docker.sock # Configure Nginx -RUN sed -i 's/worker_connections 1024/worker_connections 10240/' /etc/nginx/nginx.conf \ - && mkdir -p '/etc/nginx/dhparam' +RUN echo "\ninclude /etc/nginx/toplevel.conf.d/*.conf;" >> /etc/nginx/nginx.conf \ + && sed -i 's/worker_connections.*;$/worker_connections 10240;/' /etc/nginx/nginx.conf \ + && sed -i -e '/^\}$/{s//\}\nworker_rlimit_nofile 20480;/;:a' -e '$!N;$!ba' -e '}' /etc/nginx/nginx.conf \ + && mkdir -p '/etc/nginx/toplevel.conf.d' \ + && mkdir -p '/etc/nginx/dhparam' \ + && mkdir -p '/etc/nginx/certs' \ + && mkdir -p '/usr/share/nginx/html/errors' # Install Forego + docker-gen COPY --from=forego /usr/local/bin/forego /usr/local/bin/forego diff --git a/README.md b/README.md index edb3bb280..3baf33f3d 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,9 @@ [![Test](https://github.com/nginx-proxy/nginx-proxy/actions/workflows/test.yml/badge.svg)](https://github.com/nginx-proxy/nginx-proxy/actions/workflows/test.yml) [![GitHub release](https://img.shields.io/github/v/release/nginx-proxy/nginx-proxy)](https://github.com/nginx-proxy/nginx-proxy/releases) -![nginx 1.25.3](https://img.shields.io/badge/nginx-1.25.3-brightgreen.svg) +[![nginx 1.27.2](https://img.shields.io/badge/nginx-1.27.2-brightgreen.svg?logo=nginx)](https://nginx.org/en/CHANGES) [![Docker Image Size](https://img.shields.io/docker/image-size/nginxproxy/nginx-proxy?sort=semver)](https://hub.docker.com/r/nginxproxy/nginx-proxy "Click to view the image on Docker Hub") -[![Docker stars](https://img.shields.io/docker/stars/nginxproxy/nginx-proxy.svg)](https://hub.docker.com/r/nginxproxy/nginx-proxy 'DockerHub') -[![Docker pulls](https://img.shields.io/docker/pulls/nginxproxy/nginx-proxy.svg)](https://hub.docker.com/r/nginxproxy/nginx-proxy 'DockerHub') - +[![Docker stars](https://img.shields.io/docker/stars/nginxproxy/nginx-proxy.svg)](https://hub.docker.com/r/nginxproxy/nginx-proxy "DockerHub") +[![Docker pulls](https://img.shields.io/docker/pulls/nginxproxy/nginx-proxy.svg)](https://hub.docker.com/r/nginxproxy/nginx-proxy "DockerHub") nginx-proxy sets up a container running nginx and [docker-gen](https://github.com/nginx-proxy/docker-gen). docker-gen generates reverse proxy configs for nginx and reloads nginx when containers are started and stopped. @@ -19,7 +18,7 @@ docker run --detach \ --name nginx-proxy \ --publish 80:80 \ --volume /var/run/docker.sock:/tmp/docker.sock:ro \ - nginxproxy/nginx-proxy:1.4 + nginxproxy/nginx-proxy:1.6 ``` Then start any containers (here an nginx container) you want proxied with an env var `VIRTUAL_HOST=subdomain.yourdomain.com` @@ -34,6 +33,7 @@ docker run --detach \ Provided your DNS is setup to resolve `foo.bar.com` to the host running nginx-proxy, a request to `http://foo.bar.com` will then be routed to a container with the `VIRTUAL_HOST` env var set to `foo.bar.com` (in this case, the **your-proxied-app** container). The containers being proxied must : + - [expose](https://docs.docker.com/engine/reference/run/#expose-incoming-ports) the port to be proxied, either by using the `EXPOSE` directive in their `Dockerfile` or by using the `--expose` flag to `docker run` or `docker create`. - share at least one Docker network with the nginx-proxy container: by default, if you don't pass the `--net` flag when your nginx-proxy container is created, it will only be attached to the default bridge network. This means that it will not be able to connect to containers on networks other than bridge. @@ -48,7 +48,7 @@ The nginx-proxy images are available in two flavors. This image is based on the nginx:mainline image, itself based on the debian slim image. ```console -docker pull nginxproxy/nginx-proxy:1.4 +docker pull nginxproxy/nginx-proxy:1.6 ``` #### Alpine based version (`-alpine` suffix) @@ -56,14 +56,14 @@ docker pull nginxproxy/nginx-proxy:1.4 This image is based on the nginx:alpine image. ```console -docker pull nginxproxy/nginx-proxy:1.4-alpine +docker pull nginxproxy/nginx-proxy:1.6-alpine ``` #### :warning: a note on `latest` and `alpine`: It is not recommended to use the `latest` (`nginxproxy/nginx-proxy`, `nginxproxy/nginx-proxy:latest`) or `alpine` (`nginxproxy/nginx-proxy:alpine`) tag for production setups. -Those tags points to the latest commit in the `main` branch. They do not carry any promise of stability, and using them will probably put your nginx-proxy setup at risk of experiencing uncontrolled updates to non backward compatible versions (or versions with breaking changes). You should always specify the version you want to use explicitly to ensure your setup doesn't break when the image is updated. +[Those tags point](https://hub.docker.com/r/nginxproxy/nginx-proxy/tags) to the latest commit in the `main` branch. They do not carry any promise of stability, and using them will probably put your nginx-proxy setup at risk of experiencing uncontrolled updates to non backward compatible versions (or versions with breaking changes). You should always specify the version you want to use explicitly to ensure your setup doesn't break when the image is updated. ### Additional documentation diff --git a/docker-compose.yml b/docker-compose.yml index 809d6fa80..a261ffce0 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -9,6 +9,9 @@ services: volumes: - /var/run/docker.sock:/tmp/docker.sock:ro + # if you want to proxy based on host ports, you'll want to use the host network + # network_mode: "host" + whoami: image: jwilder/whoami environment: diff --git a/docs/README.md b/docs/README.md index 431fe6027..ecbd724a5 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,80 +1,170 @@ -### Docker Compose +# Table of Contents + +- [Virtual Hosts and Ports](#virtual-hosts-and-ports) +- [Path-based Routing](#path-based-routing) +- [Docker Networking](#docker-networking) +- [Upstream (Backend) features](#upstream-backend-features) +- [Basic Authentication Support](#basic-authentication-support) +- [Logging](#logging) +- [SSL Support](#ssl-support) +- [IPv6 Support](#ipv6-nat) +- [HTTP/2 and HTTP/3](#http2-and-http3) +- [Headers](#headers) +- [Custom Nginx Configuration](#custom-nginx-configuration) +- [TCP and UDP stream](#tcp-and-udp-stream) +- [Unhashed vs SHA1 upstream names](#unhashed-vs-sha1-upstream-names) +- [Separate Containers](#separate-containers) +- [Docker Compose](#docker-compose) +- [Troubleshooting](#troubleshooting) +- [Contributing](#contributing) + +## Virtual Hosts and Ports -```yaml -version: '2' +### Multiple Hosts -services: - nginx-proxy: - image: nginxproxy/nginx-proxy - ports: - - "80:80" - volumes: - - /var/run/docker.sock:/tmp/docker.sock:ro +If you need to support multiple virtual hosts for a container, you can separate each entry with commas. For example, `foo.bar.com,baz.bar.com,bar.com` and each host will be setup the same. - whoami: - image: jwilder/whoami - expose: - - "8000" - environment: - - VIRTUAL_HOST=whoami.example - - VIRTUAL_PORT=8000 -``` +### Wildcard Hosts + +You can also use wildcards at the beginning and the end of host name, like `*.bar.com` or `foo.bar.*`. Or even a regular expression, which can be very useful in conjunction with a wildcard DNS service like [nip.io](https://nip.io) or [sslip.io](https://sslip.io), using `~^foo\.bar\..*\.nip\.io` will match `foo.bar.127.0.0.1.nip.io`, `foo.bar.10.0.2.2.nip.io` and all other given IPs. More information about this topic can be found in the nginx documentation about [`server_names`](http://nginx.org/en/docs/http/server_names.html). + +### Default Host + +To set the default host for nginx use the env var `DEFAULT_HOST=foo.bar.com` for example ```console -docker compose up -curl -H "Host: whoami.example" localhost +docker run -d -p 80:80 -e DEFAULT_HOST=foo.bar.com -v /var/run/docker.sock:/tmp/docker.sock:ro nginxproxy/nginx-proxy ``` -Example output: +nginx-proxy will then redirect all requests to a container where `VIRTUAL_HOST` is set to `DEFAULT_HOST`, if they don't match any (other) `VIRTUAL_HOST`. Using the example above requests without matching `VIRTUAL_HOST` will be redirected to a plain nginx instance after running the following command: + ```console -I'm 5b129ab83266 +docker run -d -e VIRTUAL_HOST=foo.bar.com nginx ``` -### IPv6 support +### Virtual Ports -You can activate the IPv6 support for the nginx-proxy container by passing the value `true` to the `ENABLE_IPV6` environment variable: +When your container exposes only one port, nginx-proxy will default to this port, else to port 80. -```console -docker run -d -p 80:80 -e ENABLE_IPV6=true -v /var/run/docker.sock:/tmp/docker.sock:ro nginxproxy/nginx-proxy +If you need to specify a different port, you can set a `VIRTUAL_PORT` env var to select a different one. This variable cannot be set to more than one port. + +For each host defined into `VIRTUAL_HOST`, the associated virtual port is retrieved by order of precedence: + +1. From the `VIRTUAL_PORT` environment variable +1. From the container's exposed port if there is only one +1. From the default port 80 when none of the above methods apply + +### Multiple ports + +If your container expose more than one service on different ports and those services need to be proxied, you'll need to use the `VIRTUAL_HOST_MULTIPORTS` environment variable. This variable takes virtual host, path, port and dest definition in YAML (or JSON) form, and completely override the `VIRTUAL_HOST`, `VIRTUAL_PORT`, `VIRTUAL_PATH` and `VIRTUAL_DEST` environment variables on this container. + +The YAML syntax should be easier to write on Docker compose files, while the JSON syntax can be used for CLI invocation. + +The expected format is the following: + +```yaml +hostname: + path: + port: int + dest: string ``` -#### Scoped IPv6 Resolvers +For each hostname entry, `path`, `port` and `dest` are optional and are assigned default values when missing: -NginX does not support scoped IPv6 resolvers. In [docker-entrypoint.sh](https://github.com/nginx-proxy/nginx-proxy/tree/main/docker-entrypoint.sh) the resolvers are parsed from resolv.conf, but any scoped IPv6 addreses will be removed. +- `path` = "/" +- `port` = default port +- `dest` = "" -#### IPv6 NAT +The following examples use an hypothetical container running services on port 80, 8000 and 9000: -By default, docker uses IPv6-to-IPv4 NAT. This means all client connections from IPv6 addresses will show docker's internal IPv4 host address. To see true IPv6 client IP addresses, you must [enable IPv6](https://docs.docker.com/config/daemon/ipv6/) and use [ipv6nat](https://github.com/robbertkl/docker-ipv6nat). You must also disable the userland proxy by adding `"userland-proxy": false` to `/etc/docker/daemon.json` and restarting the daemon. +#### Multiple ports routed to different hostnames -### Multiple Hosts +```yaml +services: + multiport-container: + image: somerepo/somecontainer + container_name: multiport-container + environment: + VIRTUAL_HOST_MULTIPORTS: |- + www.example.org: + service1.example.org: + "/": + port: 8000 + service2.example.org: + "/": + port: 9000 + +# There is no path dict specified for www.example.org, so it get the default values: +# www.example.org: +# "/": +# port: 80 (default port) +# dest: "" + +# JSON equivalent: +# VIRTUAL_HOST_MULTIPORTS: |- +# { +# "www.example.org": {}, +# "service1.example.org": { "/": { "port": 8000, "dest": "" } }, +# "service2.example.org": { "/": { "port": 9000, "dest": "" } } +# } +``` -If you need to support multiple virtual hosts for a container, you can separate each entry with commas. For example, `foo.bar.com,baz.bar.com,bar.com` and each host will be setup the same. +This would result in the following proxy config: -### Virtual Ports +- `www.example.org` -> `multiport-container:80` +- `service1.example.org` -> `multiport-container:8000` +- `service2.example.org` -> `multiport-container:9000` -When your container exposes only one port, nginx-proxy will default to this port, else to port 80. +#### Multiple ports routed to same hostname and different paths -If you need to specify a different port, you can set a `VIRTUAL_PORT` env var to select a different one. This variable cannot be set to more than one port. +```yaml +services: + multiport-container: + image: somerepo/somecontainer + container_name: multiport-container + environment: + VIRTUAL_HOST_MULTIPORTS: |- + www.example.org: + "/": + "/service1": + port: 8000 + dest: "/" + "/service2": + port: 9000 + dest: "/" + +# port and dest are not specified on the / path, so this path is routed +# to the default port with the default dest value (empty string) + +# JSON equivalent: +# VIRTUAL_HOST_MULTIPORTS: |- +# { +# "www.example.org": { +# "/": {}, +# "/service1": { "port": 8000, "dest": "/" }, +# "/service2": { "port": 9000, "dest": "/" } +# } +# } +``` -For each host defined into `VIRTUAL_HOST`, the associated virtual port is retrieved by order of precedence: -1. From the `VIRTUAL_PORT` environment variable -1. From the container's exposed port if there is only one -1. From the default port 80 when none of the above methods apply +This would result in the following proxy config: -### Wildcard Hosts +- `www.example.org` -> `multiport-container:80` +- `www.example.org/service1` -> `multiport-container:8000` +- `www.example.org/service2` -> `multiport-container:9000` -You can also use wildcards at the beginning and the end of host name, like `*.bar.com` or `foo.bar.*`. Or even a regular expression, which can be very useful in conjunction with a wildcard DNS service like [nip.io](https://nip.io) or [sslip.io](https://sslip.io), using `~^foo\.bar\..*\.nip\.io` will match `foo.bar.127.0.0.1.nip.io`, `foo.bar.10.0.2.2.nip.io` and all other given IPs. More information about this topic can be found in the nginx documentation about [`server_names`](http://nginx.org/en/docs/http/server_names.html). +⬆️ [back to table of contents](#table-of-contents) -### Path-based Routing +## Path-based Routing -You can have multiple containers proxied by the same `VIRTUAL_HOST` by adding a `VIRTUAL_PATH` environment variable containing the absolute path to where the container should be mounted. For example with `VIRTUAL_HOST=foo.example.com` and `VIRTUAL_PATH=/api/v2/service`, then requests to http://foo.example.com/api/v2/service will be routed to the container. If you wish to have a container serve the root while other containers serve other paths, give the root container a `VIRTUAL_PATH` of `/`. Unmatched paths will be served by the container at `/` or will return the default nginx error page if no container has been assigned `/`. +You can have multiple containers proxied by the same `VIRTUAL_HOST` by adding a `VIRTUAL_PATH` environment variable containing the absolute path to where the container should be mounted. For example with `VIRTUAL_HOST=foo.example.com` and `VIRTUAL_PATH=/api/v2/service`, then requests to http://foo.example.com/api/v2/service will be routed to the container. If you wish to have a container serve the root while other containers serve other paths, give the root container a `VIRTUAL_PATH` of `/`. Unmatched paths will be served by the container at `/` or will return the default nginx error page if no container has been assigned `/`. It is also possible to specify multiple paths with regex locations like `VIRTUAL_PATH=~^/(app1|alternative1)/`. For further details see the nginx documentation on location blocks. This is not compatible with `VIRTUAL_DEST`. The full request URI will be forwarded to the serving container in the `X-Original-URI` header. **NOTE**: Your application needs to be able to generate links starting with `VIRTUAL_PATH`. This can be achieved by it being natively on this path or having an option to prepend this path. The application does not need to expect this path in the request. -#### VIRTUAL_DEST +### VIRTUAL_DEST This environment variable can be used to rewrite the `VIRTUAL_PATH` part of the requested URL to proxied application. The default value is empty (off). Make sure that your settings won't result in the slash missing or being doubled. Both these versions can cause troubles. @@ -88,33 +178,45 @@ $ docker run -d -e VIRTUAL_HOST=example.tld -e VIRTUAL_PATH=/app1/ -e VIRTUAL_DE In this example, the incoming request `http://example.tld/app1/foo` will be proxied as `http://app1/foo` instead of `http://app1/app1/foo`. -#### Per-VIRTUAL_PATH location configuration +### Per-VIRTUAL_PATH location configuration The same options as from [Per-VIRTUAL_HOST location configuration](#Per-VIRTUAL_HOST-location-configuration) are available on a `VIRTUAL_PATH` basis. -The only difference is that the filename gets an additional block `HASH=$(echo -n $VIRTUAL_PATH | sha1sum | awk '{ print $1 }')`. This is the sha1-hash of the `VIRTUAL_PATH` (no newline). This is done filename sanitization purposes. -The used filename is `${VIRTUAL_HOST}_${HASH}_location` +The only difference is that the filename gets an additional block `HASH=$(echo -n $VIRTUAL_PATH | sha1sum | awk '{ print $1 }')`. This is the sha1-hash of the `VIRTUAL_PATH` (no newline). This is done for filename sanitization purposes. + +The used filename is `${VIRTUAL_HOST}_${PATH_HASH}_location`, or when `VIRTUAL_HOST` is a regex, `${VIRTUAL_HOST_HASH}_${PATH_HASH}_location`. The filename of the previous example would be `example.tld_8610f6c344b4096614eab6e09d58885349f42faf_location`. -#### DEFAULT_ROOT +### DEFAULT_ROOT This environment variable of the nginx proxy container can be used to customize the return error page if no matching path is found. Furthermore it is possible to use anything which is compatible with the `return` statement of nginx. -Exception: If this is set to the string `none`, no default `location /` directive will be generated. This makes it possible for you to provide your own `location /` directive in your [`/etc/nginx/vhost.d/VIRTUAL_HOST`](#per-virtual_host) or [`/etc/nginx/vhost.d/default`](#per-virtual_host-default-configuration) files. +Exception: If this is set to the string `none`, no default `location /` directive will be generated. This makes it possible for you to provide your own `location /` directive in your [`/etc/nginx/vhost.d/VIRTUAL_HOST`](#per-virtual_host) or [`/etc/nginx/vhost.d/default`](#per-virtual_host-default-configuration) files. If unspecified, `DEFAULT_ROOT` defaults to `404`. Examples (YAML syntax): - * `DEFAULT_ROOT: "none"` prevents `nginx-proxy` from generating a default `location /` directive. - * `DEFAULT_ROOT: "418"` returns a 418 error page instead of the normal 404 one. - * `DEFAULT_ROOT: "301 https://github.com/nginx-proxy/nginx-proxy/blob/main/README.md"` redirects the client to this documentation. +- `DEFAULT_ROOT: "none"` prevents `nginx-proxy` from generating a default `location /` directive. +- `DEFAULT_ROOT: "418"` returns a 418 error page instead of the normal 404 one. +- `DEFAULT_ROOT: "301 https://github.com/nginx-proxy/nginx-proxy/blob/main/README.md"` redirects the client to this documentation. -Nginx variables such as `$scheme`, `$host`, and `$request_uri` can be used. However, care must be taken to make sure the `$` signs are escaped properly. For example, if you want to use `301 $scheme://$host/myapp1$request_uri` you should use: +Nginx variables such as `$scheme`, `$host`, and `$request_uri` can be used. However, care must be taken to make sure the `$` signs are escaped properly. For example, if you want to use `301 $scheme://$host/myapp1$request_uri` you should use: -* Bash: `DEFAULT_ROOT='301 $scheme://$host/myapp1$request_uri'` -* Docker Compose yaml: `- DEFAULT_ROOT: 301 $$scheme://$$host/myapp1$$request_uri` +- Bash: `DEFAULT_ROOT='301 $scheme://$host/myapp1$request_uri'` +- Docker Compose yaml: `- DEFAULT_ROOT: 301 $$scheme://$$host/myapp1$$request_uri` +⬆️ [back to table of contents](#table-of-contents) + +## Docker Networking + +### Custom external HTTP/HTTPS ports + +If you want to use `nginx-proxy` with different external ports that the default ones of `80` for `HTTP` traffic and `443` for `HTTPS` traffic, you'll have to use the environment variable(s) `HTTP_PORT` and/or `HTTPS_PORT` in addition to the changes to the Docker port mapping. If you change the `HTTPS` port, the redirect for `HTTPS` traffic will also be configured to redirect to the custom port. Typical usage, here with the custom ports `1080` and `10443`: + +```console +docker run -d -p 1080:1080 -p 10443:10443 -e HTTP_PORT=1080 -e HTTPS_PORT=10443 -v /var/run/docker.sock:/tmp/docker.sock:ro nginxproxy/nginx-proxy +``` ### Multiple Networks @@ -136,17 +238,9 @@ In this example, the `my-nginx-proxy` container will be connected to `my-network Proxyed containers running in host network mode **must** use the [`VIRTUAL_PORT`](#virtual-ports) environment variable, as this is the only way for `nginx-proxy` to get the correct port (or a port at all) for those containers. -### Custom external HTTP/HTTPS ports - -If you want to use `nginx-proxy` with different external ports that the default ones of `80` for `HTTP` traffic and `443` for `HTTPS` traffic, you'll have to use the environment variable(s) `HTTP_PORT` and/or `HTTPS_PORT` in addition to the changes to the Docker port mapping. If you change the `HTTPS` port, the redirect for `HTTPS` traffic will also be configured to redirect to the custom port. Typical usage, here with the custom ports `1080` and `10443`: - -```console -docker run -d -p 1080:1080 -p 10443:10443 -e HTTP_PORT=1080 -e HTTPS_PORT=10443 -v /var/run/docker.sock:/tmp/docker.sock:ro nginxproxy/nginx-proxy -``` - ### Internet vs. Local Network Access -If you allow traffic from the public internet to access your `nginx-proxy` container, you may want to restrict some containers to the internal network only, so they cannot be accessed from the public internet. On containers that should be restricted to the internal network, you should set the environment variable `NETWORK_ACCESS=internal`. By default, the *internal* network is defined as `127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16`. To change the list of networks considered internal, mount a file on the `nginx-proxy` at `/etc/nginx/network_internal.conf` with these contents, edited to suit your needs: +If you allow traffic from the public internet to access your `nginx-proxy` container, you may want to restrict some containers to the internal network only, so they cannot be accessed from the public internet. On containers that should be restricted to the internal network, you should set the environment variable `NETWORK_ACCESS=internal`. By default, the _internal_ network is defined as `127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16`. To change the list of networks considered internal, mount a file on the `nginx-proxy` at `/etc/nginx/network_internal.conf` with these contents, edited to suit your needs: ```Nginx # These networks are considered "internal" @@ -161,93 +255,156 @@ deny all; When internal-only access is enabled, external clients will be denied with an `HTTP 403 Forbidden` -> If there is a load-balancer / reverse proxy in front of `nginx-proxy` that hides the client IP (example: AWS Application/Elastic Load Balancer), you will need to use the nginx `realip` module (already installed) to extract the client's IP from the HTTP request headers. Please see the [nginx realip module configuration](http://nginx.org/en/docs/http/ngx_http_realip_module.html) for more details. This configuration can be added to a new config file and mounted in `/etc/nginx/conf.d/`. +> If there is a load-balancer / reverse proxy in front of `nginx-proxy` that hides the client IP (example: AWS Application/Elastic Load Balancer), you will need to use the nginx `realip` module (already installed) to extract the client's IP from the HTTP request headers. Please see the [nginx realip module configuration](http://nginx.org/en/docs/http/ngx_http_realip_module.html) for more details. This configuration can be added to a new config file and mounted in `/etc/nginx/conf.d/`. + +⬆️ [back to table of contents](#table-of-contents) -### SSL Backends +## Upstream (Backend) features + +### SSL Upstream If you would like the reverse proxy to connect to your backend using HTTPS instead of HTTP, set `VIRTUAL_PROTO=https` on the backend container. -> Note: If you use `VIRTUAL_PROTO=https` and your backend container exposes port 80 and 443, `nginx-proxy` will use HTTPS on port 80. This is almost certainly not what you want, so you should also include `VIRTUAL_PORT=443`. +> Note: If you use `VIRTUAL_PROTO=https` and your backend container exposes port 80 and 443, `nginx-proxy` will use HTTPS on port 80. This is almost certainly not what you want, so you should also include `VIRTUAL_PORT=443`. -### uWSGI Backends +### uWSGI Upstream If you would like to connect to uWSGI backend, set `VIRTUAL_PROTO=uwsgi` on the backend container. Your backend container should then listen on a port rather than a socket and expose that port. -### FastCGI Backends - +### FastCGI Upstream + If you would like to connect to FastCGI backend, set `VIRTUAL_PROTO=fastcgi` on the backend container. Your backend container should then listen on a port rather than a socket and expose that port. - -### FastCGI File Root Directory -If you use fastcgi,you can set `VIRTUAL_ROOT=xxx` for your root directory +#### FastCGI File Root Directory -### Custom log format +If you use fastcgi,you can set `VIRTUAL_ROOT=xxx` for your root directory -If you want to use a custom log format, you can set `LOG_FORMAT=xxx` on the proxy container. +### Upstream Server HTTP Load Balancing Support -With docker compose take care to escape the `$` character with `$$` to avoid variable interpolation. Example: `$remote_addr` becomes `$$remote_addr`. +> **Warning** +> This feature is experimental. The behavior may change (or the feature may be removed entirely) without warning in a future release, even if the release is not a new major version. If you use this feature, or if you would like to use this feature but you require changes to it first, please [provide feedback in #2195](https://github.com/nginx-proxy/nginx-proxy/discussions/2195). Once we have collected enough feedback we will promote this feature to officially supported. -### Default Host +If you have multiple containers with the same `VIRTUAL_HOST` and `VIRTUAL_PATH` settings, nginx will spread the load across all of them. To change the load balancing algorithm from nginx's default (round-robin), set the `com.github.nginx-proxy.nginx-proxy.loadbalance` label on one or more of your application containers to the desired load balancing directive. See the [`ngx_http_upstream_module` documentation](https://nginx.org/en/docs/http/ngx_http_upstream_module.html) for available directives. -To set the default host for nginx use the env var `DEFAULT_HOST=foo.bar.com` for example +> **Note** +> +> - Don't forget the terminating semicolon (`;`). +> - If you are using Docker Compose, remember to escape any dollar sign (`$`) characters (`$` becomes `$$`). -```console -docker run -d -p 80:80 -e DEFAULT_HOST=foo.bar.com -v /var/run/docker.sock:/tmp/docker.sock:ro nginxproxy/nginx-proxy +Docker Compose example: + +```yaml +services: + nginx-proxy: + image: nginxproxy/nginx-proxy + ports: + - "80:80" + volumes: + - /var/run/docker.sock:/tmp/docker.sock:ro + environment: + HTTPS_METHOD: nohttps + myapp: + image: jwilder/whoami + expose: + - "8000" + environment: + VIRTUAL_HOST: myapp.example + VIRTUAL_PORT: "8000" + labels: + com.github.nginx-proxy.nginx-proxy.loadbalance: "hash $$remote_addr;" + deploy: + replicas: 4 ``` -nginx-proxy will then redirect all requests to a container where `VIRTUAL_HOST` is set to `DEFAULT_HOST`, if they don't match any (other) `VIRTUAL_HOST`. Using the example above requests without matching `VIRTUAL_HOST` will be redirected to a plain nginx instance after running the following command: +### Upstream Server HTTP Keep-Alive Support -```console -docker run -d -e VIRTUAL_HOST=foo.bar.com nginx -``` +> **Warning** +> This feature is experimental. The behavior may change (or the feature may be removed entirely) without warning in a future release, even if the release is not a new major version. If you use this feature, or if you would like to use this feature but you require changes to it first, please [provide feedback in #2194](https://github.com/nginx-proxy/nginx-proxy/discussions/2194). Once we have collected enough feedback we will promote this feature to officially supported. -### Separate Containers +To enable HTTP keep-alive between `nginx-proxy` and backend server(s), set the `com.github.nginx-proxy.nginx-proxy.keepalive` label on the server's container either to `auto` or to the desired maximum number of idle connections. The `auto` setting will dynamically set the maximum number of idle connections to twice the number of servers listed in the corresponding `upstream{}` block, [per nginx recommendation](https://www.nginx.com/blog/avoiding-top-10-nginx-configuration-mistakes/#no-keepalives). -nginx-proxy can also be run as two separate containers using the [nginxproxy/docker-gen](https://hub.docker.com/r/nginxproxy/docker-gen) image and the official [nginx](https://registry.hub.docker.com/_/nginx/) image. +See the [nginx keepalive documentation](https://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive) and the [Docker label documentation](https://docs.docker.com/config/labels-custom-metadata/) for details. -You may want to do this to prevent having the docker socket bound to a publicly exposed container service. +⬆️ [back to table of contents](#table-of-contents) -You can demo this pattern with docker compose: +## Basic Authentication Support -```console -docker compose --file docker-compose-separate-containers.yml up -curl -H "Host: whoami.example" localhost -``` +In order to be able to secure your virtual host, you have to create a file named as its equivalent `VIRTUAL_HOST` variable (or if using a regex `VIRTUAL_HOST`, as the sha1 hash of the regex) in directory +`/etc/nginx/htpasswd/{$VIRTUAL_HOST}` -Example output: ```console -I'm 5b129ab83266 +docker run -d -p 80:80 -p 443:443 \ + -v /path/to/htpasswd:/etc/nginx/htpasswd \ + -v /path/to/certs:/etc/nginx/certs \ + -v /var/run/docker.sock:/tmp/docker.sock:ro \ + nginxproxy/nginx-proxy ``` -To run nginx proxy as a separate container you'll need to have [nginx.tmpl](https://github.com/nginx-proxy/nginx-proxy/blob/main/nginx.tmpl) on your host system. +If you want to define basic authentication for a `VIRTUAL_PATH`, you have to create a file named as `/etc/nginx/htpasswd/${VIRTUAL_HOST}_${VIRTUAL_PATH_SHA1}` +(where `$VIRTUAL_PATH_SHA1` is the SHA1 hash for the virtual path, you can use any SHA1 online generator to calculate it). -First start nginx with a volume: +You'll need apache2-utils on the machine where you plan to create the htpasswd file. Follow these [instructions](http://httpd.apache.org/docs/programs/htpasswd.html) +⬆️ [back to table of contents](#table-of-contents) -```console -docker run -d -p 80:80 --name nginx -v /tmp/nginx:/etc/nginx/conf.d -t nginx +## Logging + +The default nginx access log format is + +``` +$host $remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$upstream_addr" ``` -Then start the docker-gen container with the shared volume and template: +### Custom log format -```console -docker run --volumes-from nginx \ - -v /var/run/docker.sock:/tmp/docker.sock:ro \ - -v $(pwd):/etc/docker-gen/templates \ - -t nginxproxy/docker-gen -notify-sighup nginx -watch /etc/docker-gen/templates/nginx.tmpl /etc/nginx/conf.d/default.conf +If you want to use a custom access log format, you can set `LOG_FORMAT=xxx` on the proxy container. + +With docker compose take care to escape the `$` character with `$$` to avoid variable interpolation. Example: `$remote_addr` becomes `$$remote_addr`. + +### JSON log format + +If you want access logs in JSON format, you can set `LOG_JSON=true`. This will correctly set the escape character to `json` and the log format to : + +```json +{ + "time_local": "$time_iso8601", + "client_ip": "$http_x_forwarded_for", + "remote_addr": "$remote_addr", + "request": "$request", + "status": "$status", + "body_bytes_sent": "$body_bytes_sent", + "request_time": "$request_time", + "upstream_response_time": "$upstream_response_time", + "upstream_addr": "$upstream_addr", + "http_referrer": "$http_referer", + "http_user_agent": "$http_user_agent", + "request_id": "$request_id" +} ``` -Finally, start your containers with `VIRTUAL_HOST` environment variables. +### Log format escaping + +If you want to manually set nginx `log_format`'s `escape`, set the `LOG_FORMAT_ESCAPE` variable to [a value supported by nginx](https://nginx.org/en/docs/http/ngx_http_log_module.html#log_format). + +### Disable access logs + +To disable nginx access logs entirely, set the `DISABLE_ACCESS_LOGS` environment variable to any value. + +### Disabling colors in the container log output + +To remove colors from the container log output, set the [`NO_COLOR` environment variable to any value other than an empty string](https://no-color.org/) on the nginx-proxy container. ```console -docker run -e VIRTUAL_HOST=foo.bar.com ... +docker run --detach \ + --publish 80:80 \ + --env NO_COLOR=1 \ + --volume /var/run/docker.sock:/tmp/docker.sock:ro \ + nginxproxy/nginx-proxy ``` -### SSL Support using an ACME CA - -[acme-companion](https://github.com/nginx-proxy/acme-companion) is a lightweight companion container for the nginx-proxy. It allows the automated creation/renewal of SSL certificates using the ACME protocol. +⬆️ [back to table of contents](#table-of-contents) -### SSL Support +## SSL Support SSL is supported using single host, wildcard and SNI certificates using naming conventions for certificates or optionally specifying a cert name (for SNI) as an environment variable. @@ -261,7 +418,17 @@ The contents of `/path/to/certs` should contain the certificates and private key If you are running the container in a virtualized environment (Hyper-V, VirtualBox, etc...), /path/to/certs must exist in that environment or be made accessible to that environment. By default, Docker is not able to mount directories on the host machine to containers running in a virtual machine. -#### Diffie-Hellman Groups +### SSL Support using an ACME CA + +[acme-companion](https://github.com/nginx-proxy/acme-companion) is a lightweight companion container for the nginx-proxy. It allows the automated creation/renewal of SSL certificates using the ACME protocol. + +By default nginx-proxy generates location blocks to handle ACME HTTP Challenge. This behavior can be changed with environment variable `ACME_HTTP_CHALLENGE_LOCATION`. It accepts these values: + +- `true`: default behavior, handle ACME HTTP Challenge in all cases. +- `false`: do not handle ACME HTTP Challenge at all. +- `legacy`: legacy behavior for compatibility with older (<= `2.3`) versions of acme-companion, only handle ACME HTTP challenge when there is a certificate for the domain and `HTTPS_METHOD=redirect`. + +### Diffie-Hellman Groups [RFC7919 groups](https://datatracker.ietf.org/doc/html/rfc7919#appendix-A) with key lengths of 2048, 3072, and 4096 bits are [provided by `nginx-proxy`](https://github.com/nginx-proxy/nginx-proxy/dhparam). The ENV `DHPARAM_BITS` can be set to `2048` or `3072` to change from the default 4096-bit key. The DH key file will be located in the container at `/etc/nginx/dhparam/dhparam.pem`. Mounting a different `dhparam.pem` file at that location will override the RFC7919 key. @@ -277,23 +444,23 @@ Set `DHPARAM_SKIP` environment variable to `true` to disable using default Diffi docker run -e DHPARAM_SKIP=true .... ``` -#### Wildcard Certificates +### Wildcard Certificates Wildcard certificates and keys should be named after the domain name with a `.crt` and `.key` extension. For example `VIRTUAL_HOST=foo.bar.com` would use cert name `bar.com.crt` and `bar.com.key`. -#### SNI +### SNI -If your certificate(s) supports multiple domain names, you can start a container with `CERT_NAME=` to identify the certificate to be used. For example, a certificate for `*.foo.com` and `*.bar.com` could be named `shared.crt` and `shared.key`. A container running with `VIRTUAL_HOST=foo.bar.com` and `CERT_NAME=shared` will then use this shared cert. +If your certificate(s) supports multiple domain names, you can start a container with `CERT_NAME=` to identify the certificate to be used. For example, a certificate for `*.foo.com` and `*.bar.com` could be named `shared.crt` and `shared.key`. A container running with `VIRTUAL_HOST=foo.bar.com` and `CERT_NAME=shared` will then use this shared cert. -#### OCSP Stapling +### OCSP Stapling To enable OCSP Stapling for a domain, `nginx-proxy` looks for a PEM certificate containing the trusted CA certificate chain at `/etc/nginx/certs/.chain.pem`, where `` is the domain name in the `VIRTUAL_HOST` directive. The format of this file is a concatenation of the public PEM CA certificates starting with the intermediate CA most near the SSL certificate, down to the root CA. This is often referred to as the "SSL Certificate Chain". If found, this filename is passed to the NGINX [`ssl_trusted_certificate` directive](http://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_trusted_certificate) and OCSP Stapling is enabled. -#### How SSL Support Works +### How SSL Support Works The default SSL cipher configuration is based on the [Mozilla intermediate profile](https://wiki.mozilla.org/Security/Server_Side_TLS#Intermediate_compatibility_.28recommended.29) version 5.0 which should provide compatibility with clients back to Firefox 27, Android 4.4.2, Chrome 31, Edge, IE 11 on Windows 7, Java 8u31, OpenSSL 1.0.1, Opera 20, and Safari 9. Note that the DES-based TLS ciphers were removed for security. The configuration also enables HSTS, PFS, OCSP stapling and SSL session caches. Currently TLS 1.2 and 1.3 are supported. -If you don't require backward compatibility, you can use the [Mozilla modern profile](https://wiki.mozilla.org/Security/Server_Side_TLS#Modern_compatibility) profile instead by including the environment variable `SSL_POLICY=Mozilla-Modern` to the nginx-proxy container or to your container. This profile is compatible with clients back to Firefox 63, Android 10.0, Chrome 70, Edge 75, Java 11, OpenSSL 1.1.1, Opera 57, and Safari 12.1. Note that this profile is **not** compatible with any version of Internet Explorer. +If you don't require backward compatibility, you can use the [Mozilla modern profile](https://wiki.mozilla.org/Security/Server_Side_TLS#Modern_compatibility) profile instead by including the environment variable `SSL_POLICY=Mozilla-Modern` to the nginx-proxy container or to your container. This profile is compatible with clients back to Firefox 63, Android 10.0, Chrome 70, Edge 75, Java 11, OpenSSL 1.1.1, Opera 57, and Safari 12.1. Note that this profile is **not** compatible with any version of Internet Explorer. Complete list of policies available through the `SSL_POLICY` environment variable, including the [AWS ELB Security Policies](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/create-https-listener.html#describe-ssl-policies) and [AWS Classic ELB security policies](https://docs.aws.amazon.com/fr_fr/elasticloadbalancing/latest/classic/elb-security-policy-table.html): @@ -314,6 +481,7 @@ Complete list of policies available through the `SSL_POLICY` environment variabl Mozilla-Old + (this policy should use a 1024 bits DH key for compatibility but this container provides a 4096 bits key. The Diffie-Hellman Groups section details different methods of bypassing this, either globally or per virtual-host.) @@ -396,44 +564,74 @@ Complete list of policies available through the `SSL_POLICY` environment variabl
-Note that the `Mozilla-Old` policy should use a 1024 bits DH key for compatibility but this container provides a 4096 bits key. The [Diffie-Hellman Groups](#diffie-hellman-groups) section details different methods of bypassing this, either globally or per virtual-host. - The default behavior for the proxy when port 80 and 443 are exposed is as follows: -* If a virtual host has a usable cert, port 80 will redirect to 443 for that virtual host so that HTTPS is always preferred when available. -* If the virtual host does not have a usable cert, but `default.crt` and `default.key` exist, those will be used as the virtual host's certificate and the client browser will receive a 500 error. -* If the virtual host does not have a usable cert, and `default.crt` and `default.key` do not exist, TLS negotiation will fail (see [Missing Certificate](#missing-certificate) below). +- If a virtual host has a usable cert, port 80 will redirect to 443 for that virtual host so that HTTPS is always preferred when available. +- If the virtual host does not have a usable cert, but `default.crt` and `default.key` exist, those will be used as the virtual host's certificate and the client browser will receive a 500 error. +- If the virtual host does not have a usable cert, and `default.crt` and `default.key` do not exist, SSL handshake will be rejected (see [Missing Certificate](#missing-certificate) below). To serve traffic in both SSL and non-SSL modes without redirecting to SSL, you can include the environment variable `HTTPS_METHOD=noredirect` (the default is `HTTPS_METHOD=redirect`). You can also disable the non-SSL site entirely with `HTTPS_METHOD=nohttp`, or disable the HTTPS site with `HTTPS_METHOD=nohttps`. `HTTPS_METHOD` can be specified on each container for which you want to override the default behavior or on the proxy container to set it globally. If `HTTPS_METHOD=noredirect` is used, Strict Transport Security (HSTS) is disabled to prevent HTTPS users from being redirected by the client. If you cannot get to the HTTP site after changing this setting, your browser has probably cached the HSTS policy and is automatically redirecting you back to HTTPS. You will need to clear your browser's HSTS cache or use an incognito window / different browser. -By default, [HTTP Strict Transport Security (HSTS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security) is enabled with `max-age=31536000` for HTTPS sites. You can disable HSTS with the environment variable `HSTS=off` or use a custom HSTS configuration like `HSTS=max-age=31536000; includeSubDomains; preload`. +By default, [HTTP Strict Transport Security (HSTS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security) is enabled with `max-age=31536000` for HTTPS sites. You can disable HSTS with the environment variable `HSTS=off` or use a custom HSTS configuration like `HSTS=max-age=31536000; includeSubDomains; preload`. + +_WARNING_: HSTS will force your users to visit the HTTPS version of your site for the `max-age` time - even if they type in `http://` manually. The only way to get to an HTTP site after receiving an HSTS response is to clear your browser's HSTS cache. + +### Missing Certificate + +If no matching certificate is found for a given virtual host, nginx-proxy will: + +- configure nginx to use the default certificate (`default.crt` with `default.key`) and return a 500 error for HTTPS, +- force enable HTTP; i.e. `HTTPS_METHOD` will switch to `noredirect` if it was set to `nohttp` or `redirect`. + If this switch to HTTP is not wanted set `ENABLE_HTTP_ON_MISSING_CERT=false` (default is `true`). -*WARNING*: HSTS will force your users to visit the HTTPS version of your site for the `max-age` time - even if they type in `http://` manually. The only way to get to an HTTP site after receiving an HSTS response is to clear your browser's HSTS cache. +If the default certificate is also missing, nginx-proxy will configure nginx to reject the SSL handshake. Client browsers will render a TLS error page. As of October 2024, web browsers display the following error messages: -#### Missing Certificate +#### Chrome: -If HTTPS is enabled for a virtual host but its certificate is missing, nginx-proxy will configure nginx to use the default certificate (`default.crt` with `default.key`) and return a 500 error. +> This site can’t be reached +> +> The web page at https://example.test/ might be temporarily down or it may have moved permanently to a new web address. +> +> `ERR_SSL_UNRECOGNIZED_NAME_ALERT` -If the default certificate is also missing, nginx-proxy will configure nginx to accept HTTPS connections but fail the TLS negotiation. Client browsers will render a TLS error page. As of March 2023, web browsers display the following error messages: +#### Firefox: - * Chrome: +> Secure Connection Failed +> +> An error occurred during a connection to example.test. SSL peer has no certificate for the requested DNS name. +> +> Error code: `SSL_ERROR_UNRECOGNIZED_NAME_ALERT` +> +> - The page you are trying to view cannot be shown because the authenticity of the received data could not be verified. +> - Please contact the website owners to inform them of this problem. - > This site can't provide a secure connection - > - > example.test sent an invalid response. - > - > Try running Connectivity Diagnostics. - > - > `ERR_SSL_PROTOCOL_ERROR` +#### Safari: + +> Safari Can't Open the Page +> +> Safari can't open the page "https://example.test" because Safari can't establish a secure connection to the server "example.test". - * Firefox: +⬆️ [back to table of contents](#table-of-contents) - > Secure Connection Failed - > - > An error occurred during a connection to example.test. - > Peer reports it experienced an internal error. - > - > Error code: `SSL_ERROR_INTERNAL_ERROR_ALERT` "TLS error". +## IPv6 Support + +You can activate the IPv6 support for the nginx-proxy container by passing the value `true` to the `ENABLE_IPV6` environment variable: + +```console +docker run -d -p 80:80 -e ENABLE_IPV6=true -v /var/run/docker.sock:/tmp/docker.sock:ro nginxproxy/nginx-proxy +``` + +### Scoped IPv6 Resolvers + +Nginx does not support scoped IPv6 resolvers. In [docker-entrypoint.sh](https://github.com/nginx-proxy/nginx-proxy/blob/main/app/docker-entrypoint.sh) the resolvers are parsed from resolv.conf, but any scoped IPv6 addreses will be removed. + +### IPv6 NAT + +By default, docker uses IPv6-to-IPv4 NAT. This means all client connections from IPv6 addresses will show docker's internal IPv4 host address. To see true IPv6 client IP addresses, you must [enable IPv6](https://docs.docker.com/config/daemon/ipv6/) and use [ipv6nat](https://github.com/robbertkl/docker-ipv6nat). You must also disable the userland proxy by adding `"userland-proxy": false` to `/etc/docker/daemon.json` and restarting the daemon. + +⬆️ [back to table of contents](#table-of-contents) + +## HTTP/2 and HTTP/3 ### HTTP/2 support @@ -464,94 +662,38 @@ To enable HTTP/3 for a single proxied container, set the `com.github.nginx-proxy To enable HTTP/3 globally set the environment variable `ENABLE_HTTP3` to `true` on the nginx-proxy container. -### Basic Authentication Support - -In order to be able to secure your virtual host, you have to create a file named as its equivalent VIRTUAL_HOST variable on directory -/etc/nginx/htpasswd/$VIRTUAL_HOST - -```console -docker run -d -p 80:80 -p 443:443 \ - -v /path/to/htpasswd:/etc/nginx/htpasswd \ - -v /path/to/certs:/etc/nginx/certs \ - -v /var/run/docker.sock:/tmp/docker.sock:ro \ - nginxproxy/nginx-proxy -``` - -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) +⬆️ [back to table of contents](#table-of-contents) -### Upstream (Backend) Server HTTP Load Balancing Support - -> **Warning** -> This feature is experimental. The behavior may change (or the feature may be removed entirely) without warning in a future release, even if the release is not a new major version. If you use this feature, or if you would like to use this feature but you require changes to it first, please [provide feedback in #2195](https://github.com/nginx-proxy/nginx-proxy/discussions/2195). Once we have collected enough feedback we will promote this feature to officially supported. - -If you have multiple containers with the same `VIRTUAL_HOST` and `VIRTUAL_PATH` settings, nginx will spread the load across all of them. To change the load balancing algorithm from nginx's default (round-robin), set the `com.github.nginx-proxy.nginx-proxy.loadbalance` label on one or more of your application containers to the desired load balancing directive. See the [`ngx_http_upstream_module` documentation](https://nginx.org/en/docs/http/ngx_http_upstream_module.html) for available directives. - -> **Note** -> * Don't forget the terminating semicolon (`;`). -> * If you are using Docker Compose, remember to escape any dollar sign (`$`) characters (`$` becomes `$$`). - -Docker Compose example: - -```yaml -services: - nginx-proxy: - image: nginxproxy/nginx-proxy - ports: - - "80:80" - volumes: - - /var/run/docker.sock:/tmp/docker.sock:ro - environment: - HTTPS_METHOD: nohttps - myapp: - image: jwilder/whoami - expose: - - "8000" - environment: - VIRTUAL_HOST: myapp.example - VIRTUAL_PORT: "8000" - labels: - com.github.nginx-proxy.nginx-proxy.loadbalance: "hash $$remote_addr;" - deploy: - replicas: 4 -``` - -### Upstream (Backend) Server HTTP Keep-Alive Support - -> **Warning** -> This feature is experimental. The behavior may change (or the feature may be removed entirely) without warning in a future release, even if the release is not a new major version. If you use this feature, or if you would like to use this feature but you require changes to it first, please [provide feedback in #2194](https://github.com/nginx-proxy/nginx-proxy/discussions/2194). Once we have collected enough feedback we will promote this feature to officially supported. - -To enable HTTP keep-alive between `nginx-proxy` and backend server(s), set the `com.github.nginx-proxy.nginx-proxy.keepalive` label on the server's container either to `auto` or to the desired maximum number of idle connections. The `auto` setting will dynamically set the maximum number of idle connections to twice the number of servers listed in the corresponding `upstream{}` block, [per nginx recommendation](https://www.nginx.com/blog/avoiding-top-10-nginx-configuration-mistakes/#no-keepalives). - -See the [nginx keepalive documentation](https://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive) and the [Docker label documentation](https://docs.docker.com/config/labels-custom-metadata/) for details. - -### Headers +## Headers By default, `nginx-proxy` forwards all incoming request headers from the client to the backend server unmodified, with the following exceptions: - * `Connection`: Set to `upgrade` if the client sets the `Upgrade` header, otherwise set to `close`. (Keep-alive between `nginx-proxy` and the backend server is not supported.) - * `Proxy`: Always removed if present. This prevents attackers from using the so-called [httpoxy attack](http://httpoxy.org). There is no legitimate reason for a client to send this header, and there are many vulnerable languages / platforms (`CVE-2016-5385`, `CVE-2016-5386`, `CVE-2016-5387`, `CVE-2016-5388`, `CVE-2016-1000109`, `CVE-2016-1000110`, `CERT-VU#797896`). - * `X-Real-IP`: Set to the client's IP address. - * `X-Forwarded-For`: The client's IP address is appended to the value provided by the client. (If the client did not provide this header, it is set to the client's IP address.) - * `X-Forwarded-Host`: If the client did not provide this header or if the `TRUST_DOWNSTREAM_PROXY` environment variable is set to `false` (see below), this is set to the value of the `Host` header provided by the client. Otherwise, the header is forwarded to the backend server unmodified. - * `X-Forwarded-Proto`: If the client did not provide this header or if the `TRUST_DOWNSTREAM_PROXY` environment variable is set to `false` (see below), this is set to `http` for plain HTTP connections and `https` for TLS connections. Otherwise, the header is forwarded to the backend server unmodified. - * `X-Forwarded-Ssl`: Set to `on` if the `X-Forwarded-Proto` header sent to the backend server is `https`, otherwise set to `off`. - * `X-Forwarded-Port`: If the client did not provide this header or if the `TRUST_DOWNSTREAM_PROXY` environment variable is set to `false` (see below), this is set to the port of the server that accepted the client's request. Otherwise, the header is forwarded to the backend server unmodified. - * `X-Original-URI`: Set to the original request URI. +- `Connection`: Set to `upgrade` if the client sets the `Upgrade` header, otherwise set to `close`. (Keep-alive between `nginx-proxy` and the backend server is not supported.) +- `Proxy`: Always removed if present. This prevents attackers from using the so-called [httpoxy attack](http://httpoxy.org). There is no legitimate reason for a client to send this header, and there are many vulnerable languages / platforms (`CVE-2016-5385`, `CVE-2016-5386`, `CVE-2016-5387`, `CVE-2016-5388`, `CVE-2016-1000109`, `CVE-2016-1000110`, `CERT-VU#797896`). +- `X-Real-IP`: Set to the client's IP address. +- `X-Forwarded-For`: The client's IP address is appended to the value provided by the client. (If the client did not provide this header, it is set to the client's IP address.) +- `X-Forwarded-Host`: If the client did not provide this header or if the `TRUST_DOWNSTREAM_PROXY` environment variable is set to `false` (see below), this is set to the value of the `Host` header provided by the client. Otherwise, the header is forwarded to the backend server unmodified. +- `X-Forwarded-Proto`: If the client did not provide this header or if the `TRUST_DOWNSTREAM_PROXY` environment variable is set to `false` (see below), this is set to `http` for plain HTTP connections and `https` for TLS connections. Otherwise, the header is forwarded to the backend server unmodified. +- `X-Forwarded-Ssl`: Set to `on` if the `X-Forwarded-Proto` header sent to the backend server is `https`, otherwise set to `off`. +- `X-Forwarded-Port`: If the client did not provide this header or if the `TRUST_DOWNSTREAM_PROXY` environment variable is set to `false` (see below), this is set to the port of the server that accepted the client's request. Otherwise, the header is forwarded to the backend server unmodified. +- `X-Original-URI`: Set to the original request URI. -#### Trusting Downstream Proxy Headers +### Trusting Downstream Proxy Headers For legacy compatibility reasons, `nginx-proxy` forwards any client-supplied `X-Forwarded-Proto` (which affects the value of `X-Forwarded-Ssl`), `X-Forwarded-Host`, and `X-Forwarded-Port` headers unchecked and unmodified. To prevent malicious clients from spoofing the protocol, hostname, or port that is perceived by your backend server, you are encouraged to set the `TRUST_DOWNSTREAM_PROXY` value to `false` if: - * you do not operate a second reverse proxy downstream of `nginx-proxy`, or - * you do operate a second reverse proxy downstream of `nginx-proxy` but that proxy forwards those headers unchecked from untrusted clients. +- you do not operate a second reverse proxy downstream of `nginx-proxy`, or +- you do operate a second reverse proxy downstream of `nginx-proxy` but that proxy forwards those headers unchecked from untrusted clients. The default for `TRUST_DOWNSTREAM_PROXY` may change to `false` in a future version of `nginx-proxy`. If you require it to be enabled, you are encouraged to explicitly set it to `true` to avoid compatibility problems when upgrading. -### Custom Nginx Configuration +⬆️ [back to table of contents](#table-of-contents) + +## 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. -#### Replacing default proxy settings +### Replacing default proxy settings If you want to replace the default proxy settings for the nginx container, add a configuration file at `/etc/nginx/proxy.conf`. A file with the default settings would look like this: @@ -573,9 +715,9 @@ proxy_set_header X-Original-URI $request_uri; proxy_set_header Proxy ""; ``` -***NOTE***: If you provide this file it will replace the defaults; you may want to check the .tmpl file to make sure you have all of the needed options. +**_NOTE_**: If you provide this file it will replace the defaults; you may want to check the [nginx.tmpl](https://github.com/nginx-proxy/nginx-proxy/blob/main/nginx.tmpl) file to make sure you have all of the needed options. -#### Proxy-wide +### Proxy-wide To add settings on a proxy-wide basis, add your configuration file under `/etc/nginx/conf.d` using a name ending in `.conf`. @@ -595,9 +737,9 @@ Or it can be done by mounting in your custom configuration in your `docker run` docker run -d -p 80:80 -p 443:443 -v /path/to/my_proxy.conf:/etc/nginx/conf.d/my_proxy.conf:ro -v /var/run/docker.sock:/tmp/docker.sock:ro nginxproxy/nginx-proxy ``` -#### Per-VIRTUAL_HOST +### Per-VIRTUAL_HOST -To add settings on a per-`VIRTUAL_HOST` basis, add your configuration file under `/etc/nginx/vhost.d`. Unlike in the proxy-wide case, which allows multiple config files with any name ending in `.conf`, the per-`VIRTUAL_HOST` file must be named exactly after the `VIRTUAL_HOST`. +To add settings on a per-`VIRTUAL_HOST` basis, add your configuration file under `/etc/nginx/vhost.d`. Unlike in the proxy-wide case, which allows multiple config files with any name ending in `.conf`, the per-`VIRTUAL_HOST` file must be named exactly after the `VIRTUAL_HOST`, or if `VIRTUAL_HOST` is a regex, after the sha1 hash of the regex. In order to allow virtual hosts to be dynamically configured as backends are added and removed, it makes the most sense to mount an external directory as `/etc/nginx/vhost.d` as opposed to using derived images or mounting individual configuration files. @@ -615,13 +757,13 @@ If you are using multiple hostnames for a single container (e.g. `VIRTUAL_HOST=e ln -s /path/to/vhost.d/www.example.com /path/to/vhost.d/example.com ``` -#### Per-VIRTUAL_HOST default configuration +### Per-VIRTUAL_HOST default configuration If you want most of your virtual hosts to use a default single configuration and then override on a few specific ones, add those settings to the `/etc/nginx/vhost.d/default` file. This file will be used on any virtual host which does not have a `/etc/nginx/vhost.d/{VIRTUAL_HOST}` file associated with it. -#### Per-VIRTUAL_HOST location configuration +### Per-VIRTUAL_HOST location configuration -To add settings to the "location" block on a per-`VIRTUAL_HOST` basis, add your configuration file under `/etc/nginx/vhost.d` just like the previous section except with the suffix `_location`. +To add settings to the "location" block on a per-`VIRTUAL_HOST` basis, add your configuration file under `/etc/nginx/vhost.d` just like the per-`VIRTUAL_HOST` section except with the suffix `_location` (like this section, if your `VIRTUAl_HOST` is a regex, use the sha1 hash of the regex instead, with the suffix `_location` appended). For example, if you have a virtual host named `app.example.com` and you have configured a proxy_cache `my-cache` in another custom file, you could tell it to use a proxy cache as follows: @@ -637,19 +779,19 @@ If you are using multiple hostnames for a single container (e.g. `VIRTUAL_HOST=e ln -s /path/to/vhost.d/www.example.com /path/to/vhost.d/example.com ``` -#### Per-VIRTUAL_HOST location default configuration +### Per-VIRTUAL_HOST location default configuration If you want most of your virtual hosts to use a default single `location` block configuration and then override on a few specific ones, add those settings to the `/etc/nginx/vhost.d/default_location` file. This file will be used on any virtual host which does not have a `/etc/nginx/vhost.d/{VIRTUAL_HOST}_location` file associated with it. -#### Overriding `location` blocks +### Overriding `location` blocks -The `${VIRTUAL_HOST}_${PATH_HASH}_location`, `${VIRTUAL_HOST}_location`, and `default_location` files documented above make it possible to *augment* the generated [`location` block(s)](https://nginx.org/en/docs/http/ngx_http_core_module.html#location) in a virtual host. In some circumstances, you may need to *completely override* the `location` block for a particular combination of virtual host and path. To do this, create a file whose name follows this pattern: +The `${VIRTUAL_HOST}_${PATH_HASH}_location`, `${VIRTUAL_HOST}_location`, and `default_location` files documented above make it possible to _augment_ the generated [`location` block(s)](https://nginx.org/en/docs/http/ngx_http_core_module.html#location) in a virtual host. In some circumstances, you may need to _completely override_ the `location` block for a particular combination of virtual host and path. To do this, create a file whose name follows this pattern: ``` /etc/nginx/vhost.d/${VIRTUAL_HOST}_${PATH_HASH}_location_override ``` -where `${VIRTUAL_HOST}` is the name of the virtual host (the `VIRTUAL_HOST` environment variable) and `${PATH_HASH}` is the SHA-1 hash of the path, as [described above](#per-virtual_path-location-configuration). +where `${VIRTUAL_HOST}` is the name of the virtual host (the `VIRTUAL_HOST` environment variable), or the sha1 hash of `VIRTUAL_HOST` when it's a regex, and `${PATH_HASH}` is the SHA-1 hash of the path, as [described above](#per-virtual_path-location-configuration). For convenience, the `_${PATH_HASH}` part can be omitted if the path is `/`: @@ -657,9 +799,9 @@ For convenience, the `_${PATH_HASH}` part can be omitted if the path is `/`: /etc/nginx/vhost.d/${VIRTUAL_HOST}_location_override ``` -When an override file exists, the `location` block that is normally created by `nginx-proxy` is not generated. Instead, the override file is included via the [nginx `include` directive](https://nginx.org/en/docs/ngx_core_module.html#include). +When an override file exists, the `location` block that is normally created by `nginx-proxy` is not generated. Instead, the override file is included via the [nginx `include` directive](https://nginx.org/en/docs/ngx_core_module.html#include). -You are responsible for providing a suitable `location` block in your override file as required for your service. By default, `nginx-proxy` uses the `VIRTUAL_HOST` name as the upstream name for your application's Docker container; see [here](#unhashed-vs-sha1-upstream-names) for details. As an example, if your container has a `VIRTUAL_HOST` value of `app.example.com`, then to override the location block for `/` you would create a file named `/etc/nginx/vhost.d/app.example.com_location_override` that contains something like this: +You are responsible for providing a suitable `location` block in your override file as required for your service. By default, `nginx-proxy` uses the `VIRTUAL_HOST` name as the upstream name for your application's Docker container; see [here](#unhashed-vs-sha1-upstream-names) for details. As an example, if your container has a `VIRTUAL_HOST` value of `app.example.com`, then to override the location block for `/` you would create a file named `/etc/nginx/vhost.d/app.example.com_location_override` that contains something like this: ``` location / { @@ -667,28 +809,170 @@ location / { } ``` -#### Per-VIRTUAL_HOST `server_tokens` configuration +### Per-VIRTUAL_HOST `server_tokens` configuration + Per virtual-host `servers_tokens` directive can be configured by passing appropriate value to the `SERVER_TOKENS` environment variable. Please see the [nginx http_core module configuration](https://nginx.org/en/docs/http/ngx_http_core_module.html#server_tokens) for more details. -### Unhashed vs SHA1 upstream names +### Custom error page + +To override the default error page displayed on 50x errors, mount your custom HTML error page inside the container at `/usr/share/nginx/html/errors/50x.html`: + +```console +docker run --detach \ + --name nginx-proxy \ + --publish 80:80 \ + --volume /var/run/docker.sock:/tmp/docker.sock:ro \ + --volume /path/to/error.html:/usr/share/nginx/html/errors/50x.html:ro \ + nginxproxy/nginx-proxy +``` + +Note that this will not replace your own services error pages. + +⬆️ [back to table of contents](#table-of-contents) + +## TCP and UDP stream + +If you want to proxy non-HTTP traffic, you can use nginx's stream module. Write a configuration file and mount it inside `/etc/nginx/toplevel.conf.d`. + +```nginx +# stream.conf +stream { + upstream stream_backend { + server backend1.example.com:12345; + server backend2.example.com:12345; + server backend3.example.com:12346; + # ... + } + server { + listen 12345; + #TCP traffic will be forwarded to the "stream_backend" upstream group + proxy_pass stream_backend; + } + + server { + listen 12346; + #TCP traffic will be forwarded to the specified server + proxy_pass backend.example.com:12346; + } + + upstream dns_servers { + server 192.168.136.130:53; + server 192.168.136.131:53; + # ... + } + server { + listen 53 udp; + #UDP traffic will be forwarded to the "dns_servers" upstream group + proxy_pass dns_servers; + } + # ... +} +``` + +```console +docker run --detach \ + --name nginx-proxy \ + --publish 80:80 \ + --publish 12345:12345 \ + --publish 12346:12346 \ + --publish 53:53:udp \ + --volume /var/run/docker.sock:/tmp/docker.sock:ro \ + --volume ./stream.conf:/etc/nginx/toplevel.conf.d/stream.conf:ro \ + nginxproxy/nginx-proxy +``` + +Please note that TCP and UDP stream are not core features of nginx-proxy, so the above is provided as an example only, without any guarantee. + +⬆️ [back to table of contents](#table-of-contents) + +## Unhashed vs SHA1 upstream names By default the nginx configuration `upstream` blocks will use this block's corresponding hostname as a predictable name. However, this can cause issues in some setups (see [this issue](https://github.com/nginx-proxy/nginx-proxy/issues/1162)). In those cases you might want to switch to SHA1 names for the `upstream` blocks by setting the `SHA1_UPSTREAM_NAME` environment variable to `true` on the nginx-proxy container. Please note that using regular expressions in `VIRTUAL_HOST` will always result in a corresponding `upstream` block with an SHA1 name. -### Disabling colors in the log output +⬆️ [back to table of contents](#table-of-contents) + +## Separate Containers -To remove colors from the log output, set the [`NO_COLOR` environment variable to any value other than an empty string](https://no-color.org/) on the nginx-proxy container. +nginx-proxy can also be run as two separate containers using the [nginxproxy/docker-gen](https://hub.docker.com/r/nginxproxy/docker-gen) image and the official [nginx](https://registry.hub.docker.com/_/nginx/) image. + +You may want to do this to prevent having the docker socket bound to a publicly exposed container service. + +You can demo this pattern with docker compose: ```console -docker run --detach \ - --publish 80:80 \ - --env NO_COLOR=1 \ - --volume /var/run/docker.sock:/tmp/docker.sock:ro \ - nginxproxy/nginx-proxy +docker compose --file docker-compose-separate-containers.yml up +curl -H "Host: whoami.example" localhost ``` -### Troubleshooting +Example output: + +```console +I'm 5b129ab83266 +``` + +To run nginx proxy as a separate container you'll need to have [nginx.tmpl](https://github.com/nginx-proxy/nginx-proxy/blob/main/nginx.tmpl) on your host system. + +First start nginx with a volume: + +```console +docker run -d -p 80:80 --name nginx -v /tmp/nginx:/etc/nginx/conf.d -t nginx +``` + +Then start the docker-gen container with the shared volume and template: + +```console +docker run --volumes-from nginx \ + -v /var/run/docker.sock:/tmp/docker.sock:ro \ + -v $(pwd):/etc/docker-gen/templates \ + -t nginxproxy/docker-gen -notify-sighup nginx -watch /etc/docker-gen/templates/nginx.tmpl /etc/nginx/conf.d/default.conf +``` + +Finally, start your containers with `VIRTUAL_HOST` environment variables. + +```console +docker run -e VIRTUAL_HOST=foo.bar.com ... +``` + +⬆️ [back to table of contents](#table-of-contents) + +## Docker Compose + +```yaml +version: "2" + +services: + nginx-proxy: + image: nginxproxy/nginx-proxy + ports: + - "80:80" + volumes: + - /var/run/docker.sock:/tmp/docker.sock:ro + + whoami: + image: jwilder/whoami + expose: + - "8000" + environment: + - VIRTUAL_HOST=whoami.example + - VIRTUAL_PORT=8000 +``` + +```console +docker compose up +curl -H "Host: whoami.example" localhost +``` + +Example output: + +```console +I'm 5b129ab83266 +``` + +⬆️ [back to table of contents](#table-of-contents) + +## Troubleshooting If you can't access your `VIRTUAL_HOST`, inspect the generated nginx configuration: @@ -698,7 +982,7 @@ docker exec nginx -T Pay attention to the `upstream` definition blocks, which should look like this: -```Nginx +```nginx # foo.example.com upstream foo.example.com { ## Can be connected with "my_network" network @@ -713,15 +997,125 @@ upstream foo.example.com { ``` The effective `Port` is retrieved by order of precedence: + 1. From the `VIRTUAL_PORT` environment variable 1. From the container's exposed port if there is only one 1. From the default port 80 when none of the above methods apply -### Contributing +### Debug endpoint + +The debug endpoint can be enabled: +- globally by setting the `DEBUG_ENDPOINT` environment variable to `true` on the nginx-proxy container. +- per container by setting the `com.github.nginx-proxy.nginx-proxy.debug-endpoint` label to `true` on a proxied container. + +Enabling it will expose the endpoint at `/nginx-proxy-debug`. + +Querying the debug endpoint will show the global config, along with the virtual host and per path configs in JSON format. + +```yaml +services: + nginx-proxy: + image: nginxproxy/nginx-proxy + ports: + - "80:80" + volumes: + - /var/run/docker.sock:/tmp/docker.sock:ro + environment: + DEBUG_ENDPOINT: "true" + + test: + image: nginx + environment: + VIRTUAL_HOST: test.nginx-proxy.tld +``` + +(on the CLI, using [`jq`](https://jqlang.github.io/jq/) to format the output of `curl` is recommended) + +```console +curl -s -H "Host: test.nginx-proxy.tld" localhost/nginx-proxy-debug | jq +``` + +```json +{ + "global": { + "acme_http_challenge": "true", + "default_cert_ok": false, + "default_host": null, + "default_root_response": "404", + "enable_access_log": true, + "enable_debug_endpoint": "true", + "enable_http2": "true", + "enable_http3": "false", + "enable_http_on_missing_cert": "true", + "enable_ipv6": false, + "enable_json_logs": false, + "external_http_port": "80", + "external_https_port": "443", + "hsts": "max-age=31536000", + "https_method": "redirect", + "log_format": null, + "log_format_escape": null, + "nginx_proxy_version": "1.6.3", + "resolvers": "127.0.0.11", + "sha1_upstream_name": false, + "ssl_policy": "Mozilla-Intermediate", + "trust_downstream_proxy": true + }, + "request": { + "host": "test.nginx-proxy.tld", + "http2": "", + "http3": "", + "https": "", + "ssl_cipher": "", + "ssl_protocol": "" + }, + "vhost": { + "acme_http_challenge_enabled": true, + "acme_http_challenge_legacy": false, + "cert": "", + "cert_ok": false, + "default": false, + "enable_debug_endpoint": true, + "hostname": "test.nginx-proxy.tld", + "hsts": "max-age=31536000", + "http2_enabled": true, + "http3_enabled": false, + "https_method": "noredirect", + "is_regexp": false, + "paths": { + "/": { + "dest": "", + "keepalive": "disabled", + "network_tag": "external", + "ports": { + "legacy": [ + { + "Name": "wip-test-1" + } + ] + }, + "proto": "http", + "upstream": "test.nginx-proxy.tld" + } + }, + "server_tokens": "", + "ssl_policy": "", + "upstream_name": "test.nginx-proxy.tld", + "vhost_root": "/var/www/public" + } +} +``` + +:warning: please be aware that the debug endpoint work by rendering the JSON response straight to the nginx configuration in plaintext. nginx has an upper limit on the size of the configuration files it can parse, so only activate it when needed, and preferably on a per container basis if your setup has a large number of virtual hosts. + + +⬆️ [back to table of contents](#table-of-contents) + +## Contributing Before submitting pull requests or issues, please check github to make sure an existing issue or pull request is not already open. -#### Running Tests Locally +### Running Tests Locally To run tests, you just need to run the command below: @@ -739,3 +1133,5 @@ make test-alpine ``` You can learn more about how the test suite works and how to write new tests in the [test/README.md](https://github.com/nginx-proxy/nginx-proxy/tree/main/test/README.md) file. + +⬆️ [back to table of contents](#table-of-contents) diff --git a/nginx.tmpl b/nginx.tmpl index a0be21288..3d416c3c5 100644 --- a/nginx.tmpl +++ b/nginx.tmpl @@ -1,25 +1,44 @@ # nginx-proxy{{ if $.Env.NGINX_PROXY_VERSION }} version : {{ $.Env.NGINX_PROXY_VERSION }}{{ end }} {{- /* - * Global values. Values are stored in this map rather than in individual + * Global values. Values are stored in this map rather than in individual * global variables so that the values can be easily passed to embedded - * templates. (Go templates cannot access variables outside of their own - * scope.) + * templates (Go templates cannot access variables outside of their own + * scope) and displayed in the debug endpoint output. */}} {{- $globals := dict }} {{- $_ := set $globals "containers" $ }} {{- $_ := set $globals "Env" $.Env }} {{- $_ := set $globals "Docker" $.Docker }} {{- $_ := set $globals "CurrentContainer" (where $globals.containers "ID" $globals.Docker.CurrentContainerID | first) }} -{{- $_ := set $globals "default_cert_ok" (and (exists "/etc/nginx/certs/default.crt") (exists "/etc/nginx/certs/default.key")) }} -{{- $_ := set $globals "external_http_port" (coalesce $globals.Env.HTTP_PORT "80") }} -{{- $_ := set $globals "external_https_port" (coalesce $globals.Env.HTTPS_PORT "443") }} -{{- $_ := set $globals "sha1_upstream_name" (parseBool (coalesce $globals.Env.SHA1_UPSTREAM_NAME "false")) }} -{{- $_ := set $globals "default_root_response" (coalesce $globals.Env.DEFAULT_ROOT "404") }} -{{- $_ := set $globals "trust_downstream_proxy" (parseBool (coalesce $globals.Env.TRUST_DOWNSTREAM_PROXY "true")) }} -{{- $_ := set $globals "access_log" (or (and (not $globals.Env.DISABLE_ACCESS_LOGS) "access_log /var/log/nginx/access.log vhost;") "") }} -{{- $_ := set $globals "enable_ipv6" (parseBool (coalesce $globals.Env.ENABLE_IPV6 "false")) }} -{{- $_ := set $globals "ssl_policy" (or ($globals.Env.SSL_POLICY) "Mozilla-Intermediate") }} + +{{- $config := dict }} +{{- $_ := set $config "nginx_proxy_version" $.Env.NGINX_PROXY_VERSION }} +{{- $_ := set $config "default_cert_ok" (and (exists "/etc/nginx/certs/default.crt") (exists "/etc/nginx/certs/default.key")) }} +{{- $_ := set $config "external_http_port" ($globals.Env.HTTP_PORT | default "80") }} +{{- $_ := set $config "external_https_port" ($globals.Env.HTTPS_PORT | default "443") }} +{{- $_ := set $config "sha1_upstream_name" ($globals.Env.SHA1_UPSTREAM_NAME | default "false" | parseBool) }} +{{- $_ := set $config "default_root_response" ($globals.Env.DEFAULT_ROOT | default "404") }} +{{- $_ := set $config "trust_downstream_proxy" ($globals.Env.TRUST_DOWNSTREAM_PROXY | default "true" | parseBool) }} +{{- $_ := set $config "enable_access_log" ($globals.Env.DISABLE_ACCESS_LOGS | default "false" | parseBool | not) }} +{{- $_ := set $config "enable_ipv6" ($globals.Env.ENABLE_IPV6 | default "false" | parseBool) }} +{{- $_ := set $config "ssl_policy" ($globals.Env.SSL_POLICY | default "Mozilla-Intermediate") }} +{{- $_ := set $config "enable_debug_endpoint" ($globals.Env.DEBUG_ENDPOINT | default "false") }} +{{- $_ := set $config "hsts" ($globals.Env.HSTS | default "max-age=31536000") }} +{{- $_ := set $config "acme_http_challenge" ($globals.Env.ACME_HTTP_CHALLENGE_LOCATION | default "true") }} +{{- $_ := set $config "enable_http2" ($globals.Env.ENABLE_HTTP2 | default "true") }} +{{- $_ := set $config "enable_http3" ($globals.Env.ENABLE_HTTP3 | default "false") }} +{{- $_ := set $config "enable_http_on_missing_cert" ($globals.Env.ENABLE_HTTP_ON_MISSING_CERT | default "true") }} +{{- $_ := set $config "https_method" ($globals.Env.HTTPS_METHOD | default "redirect") }} +{{- $_ := set $config "default_host" $globals.Env.DEFAULT_HOST }} +{{- $_ := set $config "resolvers" $globals.Env.RESOLVERS }} +{{- /* LOG_JSON is a shorthand that sets logging defaults to JSON format */}} +{{- $_ := set $config "enable_json_logs" ($globals.Env.LOG_JSON | default "false" | parseBool) }} +{{- $_ := set $config "log_format" $globals.Env.LOG_FORMAT }} +{{- $_ := set $config "log_format_escape" $globals.Env.LOG_FORMAT_ESCAPE }} + +{{- $_ := set $globals "config" $config }} + {{- $_ := set $globals "vhosts" (dict) }} {{- $_ := set $globals "networks" (dict) }} # Networks available to the container running docker-gen (which are assumed to @@ -125,10 +144,10 @@ */}} {{- define "container_port" }} {{- /* If only 1 port exposed, use that as a default, else 80. */}} - # exposed ports:{{ range sortObjectsByKeysAsc $.container.Addresses "Port" }} {{ .Port }}/{{ .Proto }}{{ else }} (none){{ end }} + # exposed ports (first ten):{{ range $index, $address := (sortObjectsByKeysAsc $.container.Addresses "Port") }}{{ if lt $index 10 }} {{ $address.Port }}/{{ $address.Proto }}{{ end }}{{ else }} (none){{ end }} {{- $default_port := when (eq (len $.container.Addresses) 1) (first $.container.Addresses).Port "80" }} # default port: {{ $default_port }} - {{- $port := or $.container.Env.VIRTUAL_PORT $default_port }} + {{- $port := when (eq $.port "default") $default_port (when (eq $.port "legacy") (or $.container.Env.VIRTUAL_PORT $default_port) $.port) }} # using port: {{ $port }} {{- $addr_obj := where $.container.Addresses "Port" $port | first }} {{- if and $addr_obj $addr_obj.HostPort }} @@ -155,7 +174,7 @@ ssl_prefer_server_ciphers off; {{- else if eq .ssl_policy "Mozilla-Old" }} ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; - ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA256:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA'; + ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA256:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:@SECLEVEL=0'; ssl_prefer_server_ciphers on; {{- else if eq .ssl_policy "AWS-TLS13-1-3-2021-06" }} ssl_protocols TLSv1.3; @@ -184,11 +203,11 @@ ssl_prefer_server_ciphers on; {{- else if eq .ssl_policy "AWS-TLS13-1-1-2021-06" }} ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3; - ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:AES128-GCM-SHA256:AES128-SHA256:AES128-SHA:AES256-GCM-SHA384:AES256-SHA256:AES256-SHA'; + ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:AES128-GCM-SHA256:AES128-SHA256:AES128-SHA:AES256-GCM-SHA384:AES256-SHA256:AES256-SHA:@SECLEVEL=0'; ssl_prefer_server_ciphers on; {{- else if eq .ssl_policy "AWS-TLS13-1-0-2021-06" }} ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; - ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:AES128-GCM-SHA256:AES128-SHA256:AES128-SHA:AES256-GCM-SHA384:AES256-SHA256:AES256-SHA'; + ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:AES128-GCM-SHA256:AES128-SHA256:AES128-SHA:AES256-GCM-SHA384:AES256-SHA256:AES256-SHA:@SECLEVEL=0'; ssl_prefer_server_ciphers on; {{- else if eq .ssl_policy "AWS-FS-1-2-Res-2020-10" }} ssl_protocols TLSv1.2; @@ -204,11 +223,11 @@ ssl_prefer_server_ciphers on; {{- else if eq .ssl_policy "AWS-FS-1-1-2019-08" }} ssl_protocols TLSv1.1 TLSv1.2; - ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA'; + ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:@SECLEVEL=0'; ssl_prefer_server_ciphers on; {{- else if eq .ssl_policy "AWS-FS-2018-06" }} ssl_protocols TLSv1 TLSv1.1 TLSv1.2; - ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA'; + ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:@SECLEVEL=0'; ssl_prefer_server_ciphers on; {{- else if eq .ssl_policy "AWS-TLS-1-2-Ext-2018-06" }} ssl_protocols TLSv1.2; @@ -220,28 +239,29 @@ ssl_prefer_server_ciphers on; {{- else if eq .ssl_policy "AWS-TLS-1-1-2017-01" }} ssl_protocols TLSv1.1 TLSv1.2; - ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:AES128-GCM-SHA256:AES128-SHA256:AES128-SHA:AES256-GCM-SHA384:AES256-SHA256:AES256-SHA'; + ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:AES128-GCM-SHA256:AES128-SHA256:AES128-SHA:AES256-GCM-SHA384:AES256-SHA256:AES256-SHA:@SECLEVEL=0'; ssl_prefer_server_ciphers on; {{- else if eq .ssl_policy "AWS-2016-08" }} ssl_protocols TLSv1 TLSv1.1 TLSv1.2; - ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:AES128-GCM-SHA256:AES128-SHA256:AES128-SHA:AES256-GCM-SHA384:AES256-SHA256:AES256-SHA'; + ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:AES128-GCM-SHA256:AES128-SHA256:AES128-SHA:AES256-GCM-SHA384:AES256-SHA256:AES256-SHA:@SECLEVEL=0'; ssl_prefer_server_ciphers on; {{- else if eq .ssl_policy "AWS-2015-05" }} ssl_protocols TLSv1 TLSv1.1 TLSv1.2; - ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:AES128-GCM-SHA256:AES128-SHA256:AES128-SHA:AES256-GCM-SHA384:AES256-SHA256:AES256-SHA:DES-CBC3-SHA'; + ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:AES128-GCM-SHA256:AES128-SHA256:AES128-SHA:AES256-GCM-SHA384:AES256-SHA256:AES256-SHA:DES-CBC3-SHA:@SECLEVEL=0'; ssl_prefer_server_ciphers on; {{- else if eq .ssl_policy "AWS-2015-03" }} ssl_protocols TLSv1 TLSv1.1 TLSv1.2; - ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:AES128-GCM-SHA256:AES128-SHA256:AES128-SHA:AES256-GCM-SHA384:AES256-SHA256:AES256-SHA:DHE-DSS-AES128-SHA:DES-CBC3-SHA'; + ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:AES128-GCM-SHA256:AES128-SHA256:AES128-SHA:AES256-GCM-SHA384:AES256-SHA256:AES256-SHA:DHE-DSS-AES128-SHA:DES-CBC3-SHA:@SECLEVEL=0'; ssl_prefer_server_ciphers on; {{- else if eq .ssl_policy "AWS-2015-02" }} ssl_protocols TLSv1 TLSv1.1 TLSv1.2; - ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:AES128-GCM-SHA256:AES128-SHA256:AES128-SHA:AES256-GCM-SHA384:AES256-SHA256:AES256-SHA:DHE-DSS-AES128-SHA'; + ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:AES128-GCM-SHA256:AES128-SHA256:AES128-SHA:AES256-GCM-SHA384:AES256-SHA256:AES256-SHA:DHE-DSS-AES128-SHA:@SECLEVEL=0'; ssl_prefer_server_ciphers on; {{- end }} {{- end }} {{- define "location" }} + {{- $vpath := .VPath }} {{- $override := printf "/etc/nginx/vhost.d/%s_%s_location_override" .Host (sha1 .Path) }} {{- if and (eq .Path "/") (not (exists $override)) }} {{- $override = printf "/etc/nginx/vhost.d/%s_location_override" .Host }} @@ -249,34 +269,46 @@ {{- if exists $override }} include {{ $override }}; {{- else }} - {{- $keepalive := coalesce (first (keys (groupByLabel .Containers "com.github.nginx-proxy.nginx-proxy.keepalive"))) "disabled" }} + {{- $keepalive := $vpath.keepalive }} location {{ .Path }} { - {{- if eq .NetworkTag "internal" }} + {{- if eq $vpath.network_tag "internal" }} # Only allow traffic from internal clients include /etc/nginx/network_internal.conf; {{- end }} - {{- if eq .Proto "uwsgi" }} + {{ $proto := $vpath.proto }} + {{ $upstream := $vpath.upstream }} + {{ $dest := $vpath.dest }} + {{- if eq $proto "uwsgi" }} include uwsgi_params; - uwsgi_pass {{ trim .Proto }}://{{ trim .Upstream }}; - {{- else if eq .Proto "fastcgi" }} - root {{ trim .VhostRoot }}; + uwsgi_pass {{ trim $proto }}://{{ trim $upstream }}; + {{- else if eq $proto "fastcgi" }} + {{- if (exists "/etc/nginx/fastcgi.conf") }} + include fastcgi.conf; + {{- else if (exists "/etc/nginx/fastcgi_params") }} include fastcgi_params; - fastcgi_pass {{ trim .Upstream }}; + {{- else }} + # neither /etc/nginx/fastcgi.conf nor /etc/nginx/fastcgi_params found, fastcgi won't work + {{- end }} + root {{ trim .VhostRoot }}; + fastcgi_pass {{ trim $upstream }}; {{- if ne $keepalive "disabled" }} fastcgi_keep_conn on; {{- end }} - {{- else if eq .Proto "grpc" }} - grpc_pass {{ trim .Proto }}://{{ trim .Upstream }}; - {{- else if eq .Proto "grpcs" }} - grpc_pass {{ trim .Proto }}://{{ trim .Upstream }}; + {{- else if eq $proto "grpc" }} + grpc_pass {{ trim $proto }}://{{ trim $upstream }}; + {{- else if eq $proto "grpcs" }} + grpc_pass {{ trim $proto }}://{{ trim $upstream }}; {{- else }} - proxy_pass {{ trim .Proto }}://{{ trim .Upstream }}{{ trim .Dest }}; + proxy_pass {{ trim $proto }}://{{ trim $upstream }}{{ trim $dest }}; set $upstream_keepalive {{ if ne $keepalive "disabled" }}true{{ else }}false{{ end }}; {{- end }} - {{- if (exists (printf "/etc/nginx/htpasswd/%s" .Host)) }} - auth_basic "Restricted {{ .Host }}"; + {{- if (exists (printf "/etc/nginx/htpasswd/%s_%s" .Host (sha1 .Path) )) }} + auth_basic "Restricted {{ .Host }}{{ .Path }}"; + auth_basic_user_file {{ (printf "/etc/nginx/htpasswd/%s_%s" .Host (sha1 .Path)) }}; + {{- else if (exists (printf "/etc/nginx/htpasswd/%s" .Host)) }} + auth_basic "Restricted {{ .HostIsRegexp | ternary "access" .Host }}"; auth_basic_user_file {{ (printf "/etc/nginx/htpasswd/%s" .Host) }}; {{- end }} @@ -292,24 +324,27 @@ {{- end }} {{- define "upstream" }} -upstream {{ .Upstream }} { + {{- $path := .Path }} + {{- $vpath := .VPath }} +upstream {{ $vpath.upstream }} { {{- $servers := 0 }} - {{- $loadbalance := first (keys (groupByLabel .Containers "com.github.nginx-proxy.nginx-proxy.loadbalance")) }} + {{- $loadbalance := $vpath.loadbalance }} {{- if $loadbalance }} # From the container's loadbalance label: {{ $loadbalance }} {{- end }} - {{- range $container := .Containers }} + {{- range $port, $containers := $vpath.ports }} + {{- range $container := $containers }} # Container: {{ $container.Name }} - {{- $args := dict "globals" $.globals "container" $container }} - {{- template "container_ip" $args }} - {{- $ip := $args.ip }} - {{- $args := dict "container" $container }} - {{- template "container_port" $args }} - {{- $port := $args.port }} - {{- if $ip }} - {{- $servers = add1 $servers }} - server {{ $ip }}:{{ $port }}; + {{- $args := dict "globals" $.globals "container" $container }} + {{- template "container_ip" $args }} + {{- $ip := $args.ip }} + {{- $args = dict "container" $container "path" $path "port" $port }} + {{- template "container_port" $args }} + {{- if $ip }} + {{- $servers = add1 $servers }} + server {{ $ip }}:{{ $args.port }}; + {{- end }} {{- end }} {{- end }} {{- /* nginx-proxy/nginx-proxy#1105 */}} @@ -317,7 +352,7 @@ upstream {{ .Upstream }} { # Fallback entry server 127.0.0.1 down; {{- end }} - {{- $keepalive := coalesce (first (keys (groupByLabel .Containers "com.github.nginx-proxy.nginx-proxy.keepalive"))) "disabled" }} + {{- $keepalive := $vpath.keepalive }} {{- if and (ne $keepalive "disabled") (gt $servers 0) }} {{- if eq $keepalive "auto" }} keepalive {{ mul $servers 2 }}; @@ -328,25 +363,86 @@ upstream {{ .Upstream }} { } {{- end }} +{{- /* debug "endpoint" location template */}} +{{- define "debug_location" }} + {{- $debug_paths := dict }} + {{- range $path, $vpath := .VHost.paths }} + {{- $tmp_port := dict }} + {{- range $port, $containers := $vpath.ports }} + {{- $tmp_containers := list }} + {{- range $container := $containers }} + {{- $tmp_containers = dict "Name" $container.Name | append $tmp_containers }} + {{- end }} + {{- $_ := dict $port $tmp_containers | set $tmp_port "ports" }} + {{- $tmp_port = deepCopy $vpath | merge $tmp_port }} + {{- end }} + {{- $_ := set $debug_paths $path $tmp_port }} + {{- end }} + + {{- $debug_vhost := deepCopy .VHost }} + {{- /* If it's a regexp, do not render the Hostname to the response to avoid rendering config breaking characters */}} + {{- $_ := set $debug_vhost "hostname" (.VHost.is_regexp | ternary "Hostname is a regexp and unsafe to include in the debug response." .Hostname) }} + {{- $_ := set $debug_vhost "paths" $debug_paths }} + + {{- $debug_response := dict + "global" .GlobalConfig + "request" (dict + "host" "$host" + "https" "$https" + "http2" "$http2" + "http3" "$http3" + "ssl_cipher" "$ssl_cipher" + "ssl_protocol" "$ssl_protocol" + ) + "vhost" $debug_vhost + }} + + {{- /* + * The maximum line length in an nginx config is 4096 characters. + * If we're nearing this limit (with headroom for the rest + * of the directive), strip vhost.paths from the response. + */}} + {{- if gt (toJson $debug_response | len) 4000 }} + {{- $_ := unset $debug_vhost "paths" }} + {{- $_ := set $debug_response "warning" "Virtual paths configuration for this hostname is too large and has been stripped from response." }} + {{- end }} + + location /nginx-proxy-debug { + default_type application/json; + return 200 '{{ toJson $debug_response }}'; + } +{{- end }} + +{{- define "access_log" }} + {{- when .Enable "access_log /var/log/nginx/access.log vhost;" "" }} +{{- end }} + # If we receive X-Forwarded-Proto, pass it through; otherwise, pass along the # scheme used to connect to this server map $http_x_forwarded_proto $proxy_x_forwarded_proto { - default {{ if $globals.trust_downstream_proxy }}$http_x_forwarded_proto{{ else }}$scheme{{ end }}; + default {{ if $globals.config.trust_downstream_proxy }}$http_x_forwarded_proto{{ else }}$scheme{{ end }}; '' $scheme; } map $http_x_forwarded_host $proxy_x_forwarded_host { - default {{ if $globals.trust_downstream_proxy }}$http_x_forwarded_host{{ else }}$host{{ end }}; + default {{ if $globals.config.trust_downstream_proxy }}$http_x_forwarded_host{{ else }}$host{{ end }}; '' $host; } # If we receive X-Forwarded-Port, pass it through; otherwise, pass along the # server port the client connected to map $http_x_forwarded_port $proxy_x_forwarded_port { - default {{ if $globals.trust_downstream_proxy }}$http_x_forwarded_port{{ else }}$server_port{{ end }}; + default {{ if $globals.config.trust_downstream_proxy }}$http_x_forwarded_port{{ else }}$server_port{{ end }}; '' $server_port; } +# Include the port in the Host header sent to the container if it is non-standard +map $server_port $host_port { + default :$server_port; + 80 ''; + 443 ''; +} + # If the request from the downstream client has an "Upgrade:" header (set to any # non-empty value), pass "Connection: upgrade" to the upstream (backend) server. # Otherwise, the value for the "Connection" header depends on whether the user @@ -392,15 +488,43 @@ map $proxy_x_forwarded_proto $proxy_x_forwarded_ssl { gzip_types text/plain text/css application/javascript application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript; -log_format vhost '{{ or $globals.Env.LOG_FORMAT "$host $remote_addr - $remote_user [$time_local] \"$request\" $status $body_bytes_sent \"$http_referer\" \"$http_user_agent\" \"$upstream_addr\"" }}'; + +{{- /* See https://nginx.org/en/docs/http/ngx_http_log_module.html#log_format for details and variables + * LOG_FORMAT_ESCAPE sets the escape part of the log format + * LOG_FORMAT sets the log format + */}} +{{- $logEscape := $globals.config.log_format_escape | default "default" | printf "escape=%s" }} +{{- $logFormat := $globals.config.log_format | default `$host $remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$upstream_addr"` }} + +{{- if $globals.config.enable_json_logs }} +# JSON Logging enabled (via LOG_JSON env variable) + {{- $logEscape = $globals.config.log_format_escape | default "json" | printf "escape=%s" }} + {{- $logFormat = $globals.config.log_format | default `{"time_local":"$time_iso8601","client_ip":"$http_x_forwarded_for","remote_addr":"$remote_addr","request":"$request","status":"$status","body_bytes_sent":"$body_bytes_sent","request_time":"$request_time","upstream_response_time":"$upstream_response_time","upstream_addr":"$upstream_addr","http_referrer":"$http_referer","http_user_agent":"$http_user_agent","request_id":"$request_id"}` }} +{{- end }} + +log_format vhost {{ $logEscape }} '{{ $logFormat }}'; access_log off; -{{- template "ssl_policy" (dict "ssl_policy" $globals.ssl_policy) }} +{{- /* Lower the SSL policy of the http context + * if at least one vhost use a TLSv1 or TLSv1.1 policy + * so TLSv1 and TLSv1.1 can be enabled on those vhosts + */}} +{{- $httpContextSslPolicy := $globals.config.ssl_policy }} +{{- $inUseSslPolicies := groupByKeys $globals.containers "Env.SSL_POLICY" }} +{{- range $tls1Policy := list "AWS-TLS13-1-1-2021-06" "AWS-TLS13-1-0-2021-06" "AWS-FS-1-1-2019-08" "AWS-FS-2018-06" "AWS-TLS-1-1-2017-01" "AWS-2016-08" "AWS-2015-05" "AWS-2015-03" "AWS-2015-02" "Mozilla-Old" }} + {{- if has $tls1Policy $inUseSslPolicies }} +# Using Mozilla-Old SSL policy on the http context to allow TLSv1 and TLSv1.1 + {{- $httpContextSslPolicy = "Mozilla-Old" }} + {{- break }} + {{- end }} +{{- end }} + +{{- template "ssl_policy" (dict "ssl_policy" $httpContextSslPolicy) }} error_log /dev/stderr; -{{- if $globals.Env.RESOLVERS }} -resolver {{ $globals.Env.RESOLVERS }}; +{{- if $globals.config.resolvers }} +resolver {{ $globals.config.resolvers }}; {{- end }} {{- if (exists "/etc/nginx/proxy.conf") }} @@ -408,7 +532,7 @@ include /etc/nginx/proxy.conf; {{- else }} # HTTP 1.1 support proxy_http_version 1.1; -proxy_set_header Host $host; +proxy_set_header Host $host$host_port; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $proxy_connection; proxy_set_header X-Real-IP $remote_addr; @@ -423,36 +547,188 @@ proxy_set_header X-Original-URI $request_uri; proxy_set_header Proxy ""; {{- end }} -{{- /* - * Precompute some information about each vhost. This is done early because - * the creation of fallback servers depends on DEFAULT_HOST, HTTPS_METHOD, - * and whether there are any missing certs. - */}} -{{- range $vhost, $containers := groupByMulti $globals.containers "Env.VIRTUAL_HOST" "," }} - {{- $vhost := trim $vhost }} - {{- if not $vhost }} - {{- /* Ignore containers with VIRTUAL_HOST set to the empty string. */}} +{{- /* Precompute and store some information about vhost that use VIRTUAL_HOST_MULTIPORTS. */}} +{{- range $vhosts_yaml, $containers := groupBy $globals.containers "Env.VIRTUAL_HOST_MULTIPORTS" }} + {{- /* Print a warning in the config if VIRTUAL_HOST_MULTIPORTS can't be parsed. */}} + {{- $parsedVhosts := fromYaml $vhosts_yaml }} + {{- if (empty $parsedVhosts) }} + {{- $containerNames := list }} + {{- range $container := $containers }} + {{- $containerNames = append $containerNames $container.Name }} + {{- end }} +# /!\ WARNING: the VIRTUAL_HOST_MULTIPORTS environment variable used for {{ len $containerNames | plural "this container" "those containers" }} is not a valid YAML string: +# {{ $containerNames | join ", " }} {{- continue }} {{- end }} - {{- $certName := first (groupByKeys $containers "Env.CERT_NAME") }} - {{- $vhostCert := closest (dir "/etc/nginx/certs") (printf "%s.crt" $vhost) }} + + {{- range $hostname, $vhost := $parsedVhosts }} + {{- $vhost_data := when (hasKey $globals.vhosts $hostname) (get $globals.vhosts $hostname) (dict) }} + {{- $paths := $vhost_data.paths | default (dict) }} + + {{- if (empty $vhost) }} + {{ $vhost = dict "/" (dict) }} + {{- end }} + + {{- range $path, $vpath := $vhost }} + {{- if (empty $vpath) }} + {{- $vpath = dict "dest" "" "port" "default" }} + {{- end }} + {{- $dest := $vpath.dest | default "" }} + {{- $port := when (hasKey $vpath "port") (toString $vpath.port) "default" }} + {{- $path_data := when (hasKey $paths $path) (get $paths $path) (dict) }} + {{- $path_ports := when (hasKey $path_data "ports") (get $path_data "ports") (dict) }} + {{- $path_port_containers := when (hasKey $path_ports $port) (get $path_ports $port) (list) }} + {{- $path_port_containers = concat $path_port_containers $containers }} + {{- $_ := set $path_ports $port $path_port_containers }} + {{- $_ := set $path_data "ports" $path_ports }} + {{- if (not (hasKey $path_data "dest")) }} + {{- $_ := set $path_data "dest" $dest }} + {{- end }} + {{- $_ := set $paths $path $path_data }} + {{- end }} + {{- $_ := set $vhost_data "paths" $paths }} + {{- $is_regexp := hasPrefix "~" $hostname }} + {{- $_ := set $vhost_data "upstream_name" (when (or $is_regexp $globals.config.sha1_upstream_name) (sha1 $hostname) $hostname) }} + {{- $_ := set $globals.vhosts $hostname $vhost_data }} + {{- end }} +{{- end }} + +{{- /* Precompute and store some information about vhost that use VIRTUAL_HOST. */}} +{{- range $hostname, $containers := groupByMulti $globals.containers "Env.VIRTUAL_HOST" "," }} + {{- /* Ignore containers with VIRTUAL_HOST set to the empty string. */}} + {{- $hostname = trim $hostname }} + {{- if not $hostname }} + {{- continue }} + {{- end }} + + {{- /* Drop containers with both VIRTUAL_HOST and VIRTUAL_HOST_MULTIPORTS set + * (VIRTUAL_HOST_MULTIPORTS takes precedence thanks to the previous loop). + */}} + {{- range $_, $containers_to_drop := groupBy $containers "Env.VIRTUAL_HOST_MULTIPORTS" }} + {{- range $container := $containers_to_drop }} + {{- $containers = without $containers $container }} + {{- end }} + {{- end }} + {{- if (eq (len $containers) 0) }} + {{- continue }} + {{- end }} + + {{- $vhost_data := when (hasKey $globals.vhosts $hostname) (get $globals.vhosts $hostname) (dict) }} + {{- $paths := $vhost_data.paths | default (dict) }} + + {{- $tmp_paths := groupByWithDefault $containers "Env.VIRTUAL_PATH" "/" }} + + {{- range $path, $containers := $tmp_paths }} + {{- $dest := groupByKeys $containers "Env.VIRTUAL_DEST" | first | default "" }} + {{- $port := "legacy" }} + {{- $path_data := when (hasKey $paths $path) (get $paths $path) (dict) }} + {{- $path_ports := when (hasKey $path_data "ports") (get $path_data "ports") (dict) }} + {{- $path_port_containers := when (hasKey $path_ports $port) (get $path_ports $port) (list) }} + {{- $path_port_containers = concat $path_port_containers $containers }} + {{- $_ := set $path_ports $port $path_port_containers }} + {{- $_ := set $path_data "ports" $path_ports }} + {{- if (not (hasKey $path_data "dest")) }} + {{- $_ := set $path_data "dest" $dest }} + {{- end }} + {{- $_ := set $paths $path $path_data }} + {{- end }} + {{- $_ := set $vhost_data "paths" $paths }} + {{- $is_regexp := hasPrefix "~" $hostname }} + {{- $_ := set $vhost_data "upstream_name" (when (or $is_regexp $globals.config.sha1_upstream_name) (sha1 $hostname) $hostname) }} + {{- $_ := set $globals.vhosts $hostname $vhost_data }} +{{- end }} + +{{- /* Loop over $globals.vhosts and update it with the remaining informations about each vhost. */}} +{{- range $hostname, $vhost_data := $globals.vhosts }} + {{- $is_regexp := hasPrefix "~" $hostname }} + {{- $vhost_containers := list }} + + {{- range $path, $vpath_data := $vhost_data.paths }} + {{- $vpath_containers := list }} + {{- range $port, $vport_containers := $vpath_data.ports }} + {{ $vpath_containers = concat $vpath_containers $vport_containers }} + {{- end }} + + {{- /* Get the VIRTUAL_PROTO defined by containers w/ the same vhost-vpath, falling back to "http". */}} + {{- $proto := groupByKeys $vpath_containers "Env.VIRTUAL_PROTO" | first | default "http" | trim }} + {{- /* Get the NETWORK_ACCESS defined by containers w/ the same vhost, falling back to "external". */}} + {{- $network_tag := groupByKeys $vpath_containers "Env.NETWORK_ACCESS" | first | default "external" }} + + {{- $loadbalance := groupByLabel $vpath_containers "com.github.nginx-proxy.nginx-proxy.loadbalance" | keys | first }} + {{- $keepalive := groupByLabel $vpath_containers "com.github.nginx-proxy.nginx-proxy.keepalive" | keys | first | default "disabled" }} + + {{- $upstream := $vhost_data.upstream_name }} + {{- if (not (eq $path "/")) }} + {{- $sum := sha1 $path }} + {{- $upstream = printf "%s-%s" $upstream $sum }} + {{- end }} + + {{- $_ := set $vpath_data "proto" $proto }} + {{- $_ := set $vpath_data "network_tag" $network_tag }} + {{- $_ := set $vpath_data "upstream" $upstream }} + {{- $_ := set $vpath_data "loadbalance" $loadbalance }} + {{- $_ := set $vpath_data "keepalive" $keepalive }} + {{- $_ := set $vhost_data.paths $path $vpath_data }} + + {{ $vhost_containers = concat $vhost_containers $vpath_containers }} + {{- end }} + + {{- $certName := groupByKeys $vhost_containers "Env.CERT_NAME" | first }} + {{- $vhostCert := closest (dir "/etc/nginx/certs") (printf "%s.crt" $hostname) }} {{- $vhostCert = trimSuffix ".crt" $vhostCert }} {{- $vhostCert = trimSuffix ".key" $vhostCert }} {{- $cert := or $certName $vhostCert }} {{- $cert_ok := and (ne $cert "") (exists (printf "/etc/nginx/certs/%s.crt" $cert)) (exists (printf "/etc/nginx/certs/%s.key" $cert)) }} - {{- $default := eq $globals.Env.DEFAULT_HOST $vhost }} - {{- $https_method := or (first (groupByKeys $containers "Env.HTTPS_METHOD")) $globals.Env.HTTPS_METHOD "redirect" }} - {{- $http3 := parseBool (or (first (keys (groupByLabel $containers "com.github.nginx-proxy.nginx-proxy.http3.enable"))) $globals.Env.ENABLE_HTTP3 "false")}} - {{- $_ := set $globals.vhosts $vhost (dict + + {{- $enable_debug_endpoint := groupByLabel $vhost_containers "com.github.nginx-proxy.nginx-proxy.debug-endpoint" | keys | first | default $globals.config.enable_debug_endpoint | parseBool }} + {{- $default := eq $globals.config.default_host $hostname }} + {{- $https_method := groupByKeys $vhost_containers "Env.HTTPS_METHOD" | first | default $globals.config.https_method }} + {{- $enable_http_on_missing_cert := groupByKeys $vhost_containers "Env.ENABLE_HTTP_ON_MISSING_CERT" | first | default $globals.config.enable_http_on_missing_cert | parseBool }} + {{- /* When the certificate is missing we want to ensure that HTTP is enabled; hence switching from 'nohttp' or 'redirect' to 'noredirect' */}} + {{- if (and $enable_http_on_missing_cert (not $cert_ok) (or (eq $https_method "nohttp") (eq $https_method "redirect"))) }} + {{- $https_method = "noredirect" }} + {{- end }} + {{- $http2_enabled := groupByLabel $vhost_containers "com.github.nginx-proxy.nginx-proxy.http2.enable" | keys | first | default $globals.config.enable_http2 | parseBool }} + {{- $http3_enabled := groupByLabel $vhost_containers "com.github.nginx-proxy.nginx-proxy.http3.enable" | keys | first | default $globals.config.enable_http3 | parseBool }} + {{- $acme_http_challenge := groupByKeys $vhost_containers "Env.ACME_HTTP_CHALLENGE_LOCATION" | first | default $globals.config.acme_http_challenge }} + {{- $acme_http_challenge_legacy := eq $acme_http_challenge "legacy" }} + {{- $acme_http_challenge_enabled := false }} + {{- if (not $acme_http_challenge_legacy) }} + {{- $acme_http_challenge_enabled = parseBool $acme_http_challenge }} + {{- end }} + + {{- /* Get the SERVER_TOKENS defined by containers w/ the same vhost, falling back to "". */}} + {{- $server_tokens := groupByKeys $vhost_containers "Env.SERVER_TOKENS" | first | default "" | trim }} + + {{- /* Get the SSL_POLICY defined by containers w/ the same vhost, falling back to empty string (use default). */}} + {{- $ssl_policy := groupByKeys $vhost_containers "Env.SSL_POLICY" | first | default "" }} + + {{- /* Get the HSTS defined by containers w/ the same vhost, falling back to "max-age=31536000". */}} + {{- $hsts := groupByKeys $vhost_containers "Env.HSTS" | first | default $globals.config.hsts }} + + {{- /* Get the VIRTUAL_ROOT By containers w/ use fastcgi root */}} + {{- $vhost_root := groupByKeys $vhost_containers "Env.VIRTUAL_ROOT" | first | default "/var/www/public" }} + + {{- $vhost_data = merge $vhost_data (dict "cert" $cert "cert_ok" $cert_ok - "containers" $containers + "enable_debug_endpoint" $enable_debug_endpoint "default" $default + "hsts" $hsts "https_method" $https_method - "http3" $http3 + "http2_enabled" $http2_enabled + "http3_enabled" $http3_enabled + "is_regexp" $is_regexp + "acme_http_challenge_legacy" $acme_http_challenge_legacy + "acme_http_challenge_enabled" $acme_http_challenge_enabled + "server_tokens" $server_tokens + "ssl_policy" $ssl_policy + "vhost_root" $vhost_root ) }} + {{- $_ := set $globals.vhosts $hostname $vhost_data }} {{- end }} + {{- /* * If needed, create a catch-all fallback server to send an error code to * clients that request something from an unknown vhost. @@ -472,135 +748,96 @@ proxy_set_header Proxy ""; {{- $https_exists := false }} {{- $default_http_exists := false }} {{- $default_https_exists := false }} - {{- $http3 := false }} + {{- $http3_enabled := false }} {{- range $vhost := $globals.vhosts }} - {{- $http := or (ne $vhost.https_method "nohttp") (not $vhost.cert_ok) }} + {{- $http := ne $vhost.https_method "nohttp" }} {{- $https := ne $vhost.https_method "nohttps" }} {{- $http_exists = or $http_exists $http }} {{- $https_exists = or $https_exists $https }} {{- $default_http_exists = or $default_http_exists (and $http $vhost.default) }} {{- $default_https_exists = or $default_https_exists (and $https $vhost.default) }} - {{- $http3 = or $http3 $vhost.http3 }} + {{- $http3_enabled = or $http3_enabled $vhost.http3_enabled }} {{- end }} - {{- $fallback_http := and $http_exists (not $default_http_exists) }} - {{- $fallback_https := and $https_exists (not $default_https_exists) }} + {{- $fallback_http := not $default_http_exists }} + {{- $fallback_https := not $default_https_exists }} {{- /* * If there are no vhosts at all, create fallbacks for both plain http * and https so that clients get something more useful than a connection * refused error. */}} {{- if and (not $http_exists) (not $https_exists) }} - {{- $fallback_http = true }} {{- $fallback_https = true }} {{- end }} {{- if or $fallback_http $fallback_https }} server { server_name _; # This is just an invalid value which will never trigger on a real hostname. server_tokens off; - {{ $globals.access_log }} + {{ template "access_log" (dict "Enable" $globals.config.enable_access_log) }} http2 on; {{- if $fallback_http }} - listen {{ $globals.external_http_port }}; {{- /* Do not add `default_server` (see comment above). */}} - {{- if $globals.enable_ipv6 }} - listen [::]:{{ $globals.external_http_port }}; {{- /* Do not add `default_server` (see comment above). */}} + listen {{ $globals.config.external_http_port }}; {{- /* Do not add `default_server` (see comment above). */}} + {{- if $globals.config.enable_ipv6 }} + listen [::]:{{ $globals.config.external_http_port }}; {{- /* Do not add `default_server` (see comment above). */}} {{- end }} {{- end }} {{- if $fallback_https }} - listen {{ $globals.external_https_port }} ssl; {{- /* Do not add `default_server` (see comment above). */}} - {{- if $globals.enable_ipv6 }} - listen [::]:{{ $globals.external_https_port }} ssl; {{- /* Do not add `default_server` (see comment above). */}} + listen {{ $globals.config.external_https_port }} ssl; {{- /* Do not add `default_server` (see comment above). */}} + {{- if $globals.config.enable_ipv6 }} + listen [::]:{{ $globals.config.external_https_port }} ssl; {{- /* Do not add `default_server` (see comment above). */}} {{- end }} - {{- if $http3 }} + {{- if $http3_enabled }} http3 on; - listen {{ $globals.external_https_port }} quic reuseport; {{- /* Do not add `default_server` (see comment above). */}} - {{- if $globals.enable_ipv6 }} - listen [::]:{{ $globals.external_https_port }} quic reuseport; {{- /* Do not add `default_server` (see comment above). */}} + listen {{ $globals.config.external_https_port }} quic reuseport; {{- /* Do not add `default_server` (see comment above). */}} + {{- if $globals.config.enable_ipv6 }} + listen [::]:{{ $globals.config.external_https_port }} quic reuseport; {{- /* Do not add `default_server` (see comment above). */}} {{- end }} {{- end }} ssl_session_cache shared:SSL:50m; ssl_session_tickets off; {{- end }} - {{- if $globals.default_cert_ok }} + {{- if $globals.config.default_cert_ok }} ssl_certificate /etc/nginx/certs/default.crt; ssl_certificate_key /etc/nginx/certs/default.key; {{- else }} - # No default.crt certificate found for this vhost, so force nginx to emit a - # TLS error if the client connects via https. - {{- /* See the comment in the main `server` directive for rationale. */}} - ssl_ciphers aNULL; - set $empty ""; - ssl_certificate data:$empty; - ssl_certificate_key data:$empty; - if ($https) { - return 444; + # No default certificate found, so reject SSL handshake; + ssl_reject_handshake on; + {{- end }} + + {{- if (exists "/usr/share/nginx/html/errors/50x.html") }} + error_page 500 502 503 504 /50x.html; + location /50x.html { + root /usr/share/nginx/html/errors; + internal; } {{- end }} - return 503; + location ^~ / { + return 503; + } } {{- end }} {{- end }} -{{- range $host, $vhost := $globals.vhosts }} - {{- $cert := $vhost.cert }} - {{- $cert_ok := $vhost.cert_ok }} - {{- $containers := $vhost.containers }} +{{- range $hostname, $vhost := $globals.vhosts }} {{- $default_server := when $vhost.default "default_server" "" }} - {{- $https_method := $vhost.https_method }} - {{- $http2 := parseBool (or (first (keys (groupByLabel $containers "com.github.nginx-proxy.nginx-proxy.http2.enable"))) $globals.Env.ENABLE_HTTP2 "true")}} - {{- $http3 := parseBool (or (first (keys (groupByLabel $containers "com.github.nginx-proxy.nginx-proxy.http3.enable"))) $globals.Env.ENABLE_HTTP3 "false")}} - - {{- $is_regexp := hasPrefix "~" $host }} - {{- $upstream_name := when (or $is_regexp $globals.sha1_upstream_name) (sha1 $host) $host }} - - {{- $paths := groupBy $containers "Env.VIRTUAL_PATH" }} - {{- $nPaths := len $paths }} - {{- if eq $nPaths 0 }} - {{- $paths = dict "/" $containers }} - {{- end }} - {{- range $path, $containers := $paths }} - {{- $upstream := $upstream_name }} - {{- if gt $nPaths 0 }} - {{- $sum := sha1 $path }} - {{- $upstream = printf "%s-%s" $upstream $sum }} - {{- end }} -# {{ $host }}{{ $path }} -{{ template "upstream" (dict "globals" $globals "Upstream" $upstream "Containers" $containers) }} + {{- range $path, $vpath := $vhost.paths }} +# {{ $hostname }}{{ $path }} + {{ template "upstream" (dict "globals" $globals "Path" $path "VPath" $vpath) }} {{- end }} - {{- /* - * Get the SERVER_TOKENS defined by containers w/ the same vhost, - * falling back to "". - */}} - {{- $server_tokens := trim (or (first (groupByKeys $containers "Env.SERVER_TOKENS")) "") }} - - {{- /* - * Get the SSL_POLICY defined by containers w/ the same vhost, falling - * back to empty string (use default). - */}} - {{- $ssl_policy := or (first (groupByKeys $containers "Env.SSL_POLICY")) "" }} - - {{- /* - * Get the HSTS defined by containers w/ the same vhost, falling back to - * "max-age=31536000". - */}} - {{- $hsts := or (first (groupByKeys $containers "Env.HSTS")) (or $globals.Env.HSTS "max-age=31536000") }} - - {{- /* Get the VIRTUAL_ROOT By containers w/ use fastcgi root */}} - {{- $vhost_root := or (first (groupByKeys $containers "Env.VIRTUAL_ROOT")) "/var/www/public" }} - - {{- if and $cert_ok (eq $https_method "redirect") }} + {{- if (eq $vhost.https_method "redirect") }} server { - server_name {{ $host }}; - {{- if $server_tokens }} - server_tokens {{ $server_tokens }}; + server_name {{ $hostname }}; + {{- if $vhost.server_tokens }} + server_tokens {{ $vhost.server_tokens }}; {{- end }} - {{ $globals.access_log }} - listen {{ $globals.external_http_port }} {{ $default_server }}; - {{- if $globals.enable_ipv6 }} - listen [::]:{{ $globals.external_http_port }} {{ $default_server }}; + {{ template "access_log" (dict "Enable" $globals.config.enable_access_log) }} + listen {{ $globals.config.external_http_port }} {{ $default_server }}; + {{- if $globals.config.enable_ipv6 }} + listen [::]:{{ $globals.config.external_http_port }} {{ $default_server }}; {{- end }} + {{- if (or $vhost.acme_http_challenge_legacy $vhost.acme_http_challenge_enabled) }} # Do not HTTPS redirect Let's Encrypt ACME challenge location ^~ /.well-known/acme-challenge/ { auth_basic off; @@ -610,75 +847,107 @@ server { try_files $uri =404; break; } + {{- end }} + + {{- if $vhost.enable_debug_endpoint }} + {{ template "debug_location" (dict "GlobalConfig" $globals.config "Hostname" $hostname "VHost" $vhost) }} + {{- end }} location / { - {{- if eq $globals.external_https_port "443" }} + {{- if eq $globals.config.external_https_port "443" }} return 301 https://$host$request_uri; {{- else }} - return 301 https://$host:{{ $globals.external_https_port }}$request_uri; + return 301 https://$host:{{ $globals.config.external_https_port }}$request_uri; {{- end }} } } {{- end }} server { - server_name {{ $host }}; - {{- if $server_tokens }} - server_tokens {{ $server_tokens }}; + {{- if $vhost.is_regexp }} + {{- if or + (printf "/etc/nginx/vhost.d/%s" $hostname | exists) + (printf "/etc/nginx/vhost.d/%s_location" $hostname | exists) + (printf "/etc/nginx/vhost.d/%s_location_override" $hostname | exists) + (printf "/etc/nginx/htpasswd/%s" $hostname | exists) + }} + # https://github.com/nginx-proxy/nginx-proxy/issues/2529#issuecomment-2437609249 + # Support for vhost config file(s) named like a regexp ({{ $hostname }}) has been removed from nginx-proxy. + # Please name your vhost config file(s) with the sha1 of the regexp instead ({{ $hostname }} -> {{ sha1 $hostname }}) : + # - /etc/nginx/vhost.d/{{ sha1 $hostname }} + # - /etc/nginx/vhost.d/{{ sha1 $hostname }}_location + # - /etc/nginx/vhost.d/{{ sha1 $hostname }}_location_override + # - /etc/nginx/htpasswd/{{ sha1 $hostname }} + {{- end }} + {{- end }} + + server_name {{ $hostname }}; + {{- if $vhost.server_tokens }} + server_tokens {{ $vhost.server_tokens }}; {{- end }} - {{ $globals.access_log }} - {{- if $http2 }} + {{ template "access_log" (dict "Enable" $globals.config.enable_access_log) }} + {{- if $vhost.http2_enabled }} http2 on; {{- end }} - {{- if or (eq $https_method "nohttps") (not $cert_ok) (eq $https_method "noredirect") }} - listen {{ $globals.external_http_port }} {{ $default_server }}; - {{- if $globals.enable_ipv6 }} - listen [::]:{{ $globals.external_http_port }} {{ $default_server }}; + {{- if or (eq $vhost.https_method "nohttps") (eq $vhost.https_method "noredirect") }} + listen {{ $globals.config.external_http_port }} {{ $default_server }}; + {{- if $globals.config.enable_ipv6 }} + listen [::]:{{ $globals.config.external_http_port }} {{ $default_server }}; + {{- end }} + + {{- if (and (eq $vhost.https_method "noredirect") $vhost.acme_http_challenge_enabled) }} + location /.well-known/acme-challenge/ { + auth_basic off; + allow all; + root /usr/share/nginx/html; + try_files $uri =404; + break; + } {{- end }} {{- end }} - {{- if ne $https_method "nohttps" }} - listen {{ $globals.external_https_port }} ssl {{ $default_server }}; - {{- if $globals.enable_ipv6 }} - listen [::]:{{ $globals.external_https_port }} ssl {{ $default_server }}; + {{- if ne $vhost.https_method "nohttps" }} + listen {{ $globals.config.external_https_port }} ssl {{ $default_server }}; + {{- if $globals.config.enable_ipv6 }} + listen [::]:{{ $globals.config.external_https_port }} ssl {{ $default_server }}; {{- end }} - {{- if $http3 }} + {{- if $vhost.http3_enabled }} http3 on; - add_header alt-svc 'h3=":{{ $globals.external_https_port }}"; ma=86400;'; - listen {{ $globals.external_https_port }} quic {{ $default_server }}; - {{- if $globals.enable_ipv6 }} - listen [::]:{{ $globals.external_https_port }} quic {{ $default_server }}; + add_header alt-svc 'h3=":{{ $globals.config.external_https_port }}"; ma=86400;'; + listen {{ $globals.config.external_https_port }} quic {{ $default_server }}; + {{- if $globals.config.enable_ipv6 }} + listen [::]:{{ $globals.config.external_https_port }} quic {{ $default_server }}; {{- end }} {{- end }} - {{- if $cert_ok }} - {{- template "ssl_policy" (dict "ssl_policy" $ssl_policy) }} + {{- if $vhost.cert_ok }} + {{- template "ssl_policy" (dict "ssl_policy" $vhost.ssl_policy) }} ssl_session_timeout 5m; ssl_session_cache shared:SSL:50m; ssl_session_tickets off; - ssl_certificate /etc/nginx/certs/{{ (printf "%s.crt" $cert) }}; - ssl_certificate_key /etc/nginx/certs/{{ (printf "%s.key" $cert) }}; + ssl_certificate /etc/nginx/certs/{{ (printf "%s.crt" $vhost.cert) }}; + ssl_certificate_key /etc/nginx/certs/{{ (printf "%s.key" $vhost.cert) }}; - {{- if (exists (printf "/etc/nginx/certs/%s.dhparam.pem" $cert)) }} - ssl_dhparam {{ printf "/etc/nginx/certs/%s.dhparam.pem" $cert }}; + {{- if (exists (printf "/etc/nginx/certs/%s.dhparam.pem" $vhost.cert)) }} + ssl_dhparam {{ printf "/etc/nginx/certs/%s.dhparam.pem" $vhost.cert }}; {{- end }} - {{- if (exists (printf "/etc/nginx/certs/%s.chain.pem" $cert)) }} + {{- if (exists (printf "/etc/nginx/certs/%s.chain.pem" $vhost.cert)) }} ssl_stapling on; ssl_stapling_verify on; - ssl_trusted_certificate {{ printf "/etc/nginx/certs/%s.chain.pem" $cert }}; + ssl_trusted_certificate {{ printf "/etc/nginx/certs/%s.chain.pem" $vhost.cert }}; {{- end }} - {{- if (not (or (eq $https_method "noredirect") (eq $hsts "off"))) }} + {{- if (not (or (eq $vhost.https_method "noredirect") (eq $vhost.hsts "off"))) }} set $sts_header ""; if ($https) { - set $sts_header "{{ trim $hsts }}"; + set $sts_header "{{ trim $vhost.hsts }}"; } add_header Strict-Transport-Security $sts_header always; {{- end }} - {{- else if $globals.default_cert_ok }} + {{- else if $globals.config.default_cert_ok }} # No certificate found for this vhost, so use the default certificate and # return an error code if the user connects via https. ssl_certificate /etc/nginx/certs/default.crt; @@ -687,66 +956,36 @@ server { return 500; } {{- else }} - # No certificate found for this vhost, so force nginx to emit a TLS error if - # the client connects via https. - {{- /* - * The alternative is to not provide an https server for this - * vhost, which would either cause the user to see the wrong - * vhost (if there is another vhost with a certificate) or a - * connection refused error (if there is no other vhost with a - * certificate). A TLS error is easier to troubleshoot, and is - * safer than serving the wrong vhost. Also see - * . - */}} - ssl_ciphers aNULL; - set $empty ""; - ssl_certificate data:$empty; - ssl_certificate_key data:$empty; - if ($https) { - return 444; - } + # No certificate for this vhost nor default certificate found, so reject SSL handshake. + ssl_reject_handshake on; {{- end }} {{- end }} - {{- if (exists (printf "/etc/nginx/vhost.d/%s" $host)) }} - include {{ printf "/etc/nginx/vhost.d/%s" $host }}; + {{- $vhostFileName := $vhost.is_regexp | ternary (sha1 $hostname) $hostname }} + + {{- if (exists (printf "/etc/nginx/vhost.d/%s" $vhostFileName)) }} + include {{ printf "/etc/nginx/vhost.d/%s" $vhostFileName }}; {{- else if (exists "/etc/nginx/vhost.d/default") }} include /etc/nginx/vhost.d/default; {{- end }} - {{- range $path, $containers := $paths }} - {{- /* - * Get the VIRTUAL_PROTO defined by containers w/ the same - * vhost-vpath, falling back to "http". - */}} - {{- $proto := trim (or (first (groupByKeys $containers "Env.VIRTUAL_PROTO")) "http") }} + {{- if $vhost.enable_debug_endpoint }} + {{ template "debug_location" (dict "GlobalConfig" $globals.config "Hostname" $hostname "VHost" $vhost) }} + {{- end }} - {{- /* - * Get the NETWORK_ACCESS defined by containers w/ the same vhost, - * falling back to "external". - */}} - {{- $network_tag := or (first (groupByKeys $containers "Env.NETWORK_ACCESS")) "external" }} - {{- $upstream := $upstream_name }} - {{- $dest := "" }} - {{- if gt $nPaths 0 }} - {{- $sum := sha1 $path }} - {{- $upstream = printf "%s-%s" $upstream $sum }} - {{- $dest = (or (first (groupByKeys $containers "Env.VIRTUAL_DEST")) "") }} - {{- end }} + {{- range $path, $vpath := $vhost.paths }} {{- template "location" (dict "Path" $path - "Proto" $proto - "Upstream" $upstream - "Host" $host - "VhostRoot" $vhost_root - "Dest" $dest - "NetworkTag" $network_tag - "Containers" $containers + "Host" $vhostFileName + "HostIsRegexp" $vhost.is_regexp + "VhostRoot" $vhost.vhost_root + "VPath" $vpath ) }} {{- end }} - {{- if and (not (contains $paths "/")) (ne $globals.default_root_response "none")}} + + {{- if and (not (contains $vhost.paths "/")) (ne $globals.config.default_root_response "none")}} location / { - return {{ $globals.default_root_response }}; + return {{ $globals.config.default_root_response }}; } {{- end }} } diff --git a/test/certs/create_server_certificate.sh b/test/certs/create_server_certificate.sh index 0789a22e7..01413ee34 100755 --- a/test/certs/create_server_certificate.sh +++ b/test/certs/create_server_certificate.sh @@ -24,7 +24,7 @@ fi # Create a nginx container (which conveniently provides the `openssl` command) ############################################################################### -CONTAINER=$(docker run -d -v $DIR:/work -w /work -e SAN="$ALTERNATE_DOMAINS" nginx:1.25.3) +CONTAINER=$(docker run -d -v $DIR:/work -w /work -e SAN="$ALTERNATE_DOMAINS" nginx:1.27.2) # Configure openssl docker exec $CONTAINER bash -c ' mkdir -p /ca/{certs,crl,private,newcerts} 2>/dev/null diff --git a/test/conftest.py b/test/conftest.py index 7fa269a61..dda20f60b 100644 --- a/test/conftest.py +++ b/test/conftest.py @@ -510,6 +510,13 @@ def nginxproxy(): yield requests_for_docker() +@pytest.fixture() +def acme_challenge_path(): + """ + Provides fake Let's Encrypt ACME challenge path used in certain tests + """ + return ".well-known/acme-challenge/test-filename" + ############################################################################### # # Py.test hooks diff --git a/test/requirements/python-requirements.txt b/test/requirements/python-requirements.txt index d5033424a..e8236945c 100644 --- a/test/requirements/python-requirements.txt +++ b/test/requirements/python-requirements.txt @@ -1,4 +1,4 @@ backoff==2.2.1 -docker==7.0.0 -pytest==7.4.4 -requests==2.31.0 +docker==7.1.0 +pytest==8.3.3 +requests==2.32.3 diff --git a/test/requirements/web/Dockerfile b/test/requirements/web/Dockerfile index 923ed79c4..da755534c 100644 --- a/test/requirements/web/Dockerfile +++ b/test/requirements/web/Dockerfile @@ -1,6 +1,7 @@ # Docker Image running one (or multiple) webservers listening on all given ports from WEB_PORTS environment variable -FROM python:3 +FROM python:3-alpine +RUN apk add --no-cache bash COPY ./webserver.py / COPY ./entrypoint.sh / WORKDIR /opt diff --git a/test/requirements/web/entrypoint.sh b/test/requirements/web/entrypoint.sh index 3015c115d..be9f9c365 100644 --- a/test/requirements/web/entrypoint.sh +++ b/test/requirements/web/entrypoint.sh @@ -5,11 +5,11 @@ trap '[ ${#PIDS[@]} -gt 0 ] && kill -TERM ${PIDS[@]}' TERM declare -a PIDS for port in $WEB_PORTS; do - echo starting a web server listening on port $port; - /webserver.py $port & + echo starting a web server listening on port "$port"; + /webserver.py "$port" & PIDS+=($!) done -wait ${PIDS[@]} +wait "${PIDS[@]}" trap - TERM -wait ${PIDS[@]} +wait "${PIDS[@]}" diff --git a/test/requirements/web/webserver.py b/test/requirements/web/webserver.py index b8e81c062..c4750bdb1 100755 --- a/test/requirements/web/webserver.py +++ b/test/requirements/web/webserver.py @@ -14,8 +14,8 @@ def do_GET(self): response_body += self.headers.as_string() elif self.path == "/port": response_body += f"answer from port {PORT}\n" - elif re.match("/status/(\d+)", self.path): - result = re.match("/status/(\d+)", self.path) + elif re.match(r"/status/(\d+)", self.path): + result = re.match(r"/status/(\d+)", self.path) response_code = int(result.group(1)) response_body += f"answer with response code {response_code}\n" elif self.path == "/": diff --git a/test/stress_tests/test_deleted_cert/README.md b/test/stress_tests/test_deleted_cert/README.md deleted file mode 100644 index 9fac0b908..000000000 --- a/test/stress_tests/test_deleted_cert/README.md +++ /dev/null @@ -1,5 +0,0 @@ -Test the behavior of nginx-proxy when restarted after deleting a certificate file is was using. - -1. nginx-proxy is created with a virtual host having a certificate -1. while nginx-proxy is running, the certificate file is deleted -1. nginx-proxy is then restarted (without removing the container) diff --git a/test/stress_tests/test_deleted_cert/certs/web.nginx-proxy.crt b/test/stress_tests/test_deleted_cert/certs/web.nginx-proxy.crt deleted file mode 100644 index 2c92efee7..000000000 --- a/test/stress_tests/test_deleted_cert/certs/web.nginx-proxy.crt +++ /dev/null @@ -1,70 +0,0 @@ -Certificate: - Data: - Version: 3 (0x2) - Serial Number: 4096 (0x1000) - Signature Algorithm: sha256WithRSAEncryption - Issuer: O=nginx-proxy test suite, CN=www.nginx-proxy.tld - Validity - Not Before: Feb 17 23:20:54 2017 GMT - Not After : Jul 5 23:20:54 2044 GMT - Subject: CN=web.nginx-proxy - Subject Public Key Info: - Public Key Algorithm: rsaEncryption - Public-Key: (2048 bit) - Modulus: - 00:b6:27:63:a5:c6:e8:f4:7a:94:0e:cc:a2:62:76: - 6d:5d:33:6f:cf:19:fc:e7:e5:bb:0e:0e:d0:7c:4f: - 73:4c:48:2b:17:d1:4d:d5:9f:42:08:73:84:54:8c: - 86:d2:c5:da:59:01:3f:42:22:e0:36:f0:dc:ab:de: - 0a:bd:26:2b:22:13:87:a6:1f:23:ef:0e:99:27:8b: - 15:4a:1b:ef:93:c9:6b:91:de:a0:02:0c:62:bb:cc: - 56:37:e8:25:92:c3:1f:f1:69:d8:7c:a8:33:e0:89: - ce:14:67:a0:39:77:88:91:e6:a3:07:97:90:22:88: - d0:79:18:63:fb:6f:7e:ee:2b:42:7e:23:f5:e7:da: - e9:ee:6a:fa:96:65:9f:e1:2b:15:49:c8:cd:2d:ce: - 86:4f:2c:2a:67:79:bf:41:30:14:cc:f6:0f:14:74: - 9e:b6:d3:d0:3b:f0:1b:b8:e8:19:2a:fd:d6:fd:dc: - 4b:4e:65:7d:9b:bf:37:7e:2d:35:22:2e:74:90:ce: - 41:35:3d:41:a0:99:db:97:1f:bf:3e:18:3c:48:fb: - da:df:c6:4e:4e:b9:67:b8:10:d5:a5:13:03:c4:b7: - 65:e7:aa:f0:14:4b:d3:4d:ea:fe:8f:69:cf:50:21: - 63:27:cf:9e:4c:67:15:7b:3f:3b:da:cb:17:80:61: - 1e:25 - Exponent: 65537 (0x10001) - X509v3 extensions: - X509v3 Subject Alternative Name: - DNS:web.nginx-proxy - Signature Algorithm: sha256WithRSAEncryption - 09:31:be:db:4e:b0:b6:68:da:ae:5b:16:51:29:fc:9f:61:b6: - 5a:2f:3c:35:ef:67:76:97:b0:34:4e:3b:b4:d6:88:19:4f:84: - 2e:73:d3:c0:3a:4c:41:54:6c:bb:67:89:67:ad:25:55:d7:d4: - 80:fe:a7:3f:3d:9e:f1:34:96:d8:da:5a:78:51:c0:63:f1:52: - 29:35:55:f4:7d:70:1c:d3:96:62:7f:64:86:81:52:27:c4:c6: - 10:13:c6:73:56:4d:32:d0:b3:c3:c8:2c:25:83:e4:2b:1d:d4: - 74:30:e5:85:af:2d:b6:a5:6b:fe:5d:d3:3c:00:58:94:f4:6a: - f5:a6:1d:cf:f9:ed:d5:27:ed:13:24:b2:4f:2b:f3:b8:e4:af: - 0c:1d:fe:e0:6a:01:5e:a2:44:ff:3e:96:fa:6c:39:a3:51:37: - f3:72:55:d8:2d:29:6e:de:95:b9:d8:e3:1e:65:a5:9c:0d:79: - 2d:39:ab:c7:ac:16:b6:a5:71:4b:35:a4:6c:72:47:1b:72:9c: - 67:58:c1:fc:f6:7f:a7:73:50:7b:d6:27:57:74:a1:31:38:a7: - 31:e3:b9:d4:c9:45:33:ec:ed:16:cf:c5:bd:d0:03:b1:45:3f: - 68:0d:91:5c:26:4e:37:05:74:ed:3e:75:5e:ca:5e:ee:e2:51: - 4b:da:08:99 ------BEGIN CERTIFICATE----- -MIIC8zCCAdugAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPzEfMB0GA1UECgwWbmdp -bngtcHJveHkgdGVzdCBzdWl0ZTEcMBoGA1UEAwwTd3d3Lm5naW54LXByb3h5LnRs -ZDAeFw0xNzAyMTcyMzIwNTRaFw00NDA3MDUyMzIwNTRaMBoxGDAWBgNVBAMMD3dl -Yi5uZ2lueC1wcm94eTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALYn -Y6XG6PR6lA7MomJ2bV0zb88Z/Ofluw4O0HxPc0xIKxfRTdWfQghzhFSMhtLF2lkB -P0Ii4Dbw3KveCr0mKyITh6YfI+8OmSeLFUob75PJa5HeoAIMYrvMVjfoJZLDH/Fp -2HyoM+CJzhRnoDl3iJHmoweXkCKI0HkYY/tvfu4rQn4j9efa6e5q+pZln+ErFUnI -zS3Ohk8sKmd5v0EwFMz2DxR0nrbT0DvwG7joGSr91v3cS05lfZu/N34tNSIudJDO -QTU9QaCZ25cfvz4YPEj72t/GTk65Z7gQ1aUTA8S3Zeeq8BRL003q/o9pz1AhYyfP -nkxnFXs/O9rLF4BhHiUCAwEAAaMeMBwwGgYDVR0RBBMwEYIPd2ViLm5naW54LXBy -b3h5MA0GCSqGSIb3DQEBCwUAA4IBAQAJMb7bTrC2aNquWxZRKfyfYbZaLzw172d2 -l7A0Tju01ogZT4Quc9PAOkxBVGy7Z4lnrSVV19SA/qc/PZ7xNJbY2lp4UcBj8VIp -NVX0fXAc05Zif2SGgVInxMYQE8ZzVk0y0LPDyCwlg+QrHdR0MOWFry22pWv+XdM8 -AFiU9Gr1ph3P+e3VJ+0TJLJPK/O45K8MHf7gagFeokT/Ppb6bDmjUTfzclXYLSlu -3pW52OMeZaWcDXktOavHrBa2pXFLNaRsckcbcpxnWMH89n+nc1B71idXdKExOKcx -47nUyUUz7O0Wz8W90AOxRT9oDZFcJk43BXTtPnVeyl7u4lFL2giZ ------END CERTIFICATE----- diff --git a/test/stress_tests/test_deleted_cert/certs/web.nginx-proxy.key b/test/stress_tests/test_deleted_cert/certs/web.nginx-proxy.key deleted file mode 100644 index dca1c9983..000000000 --- a/test/stress_tests/test_deleted_cert/certs/web.nginx-proxy.key +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEAtidjpcbo9HqUDsyiYnZtXTNvzxn85+W7Dg7QfE9zTEgrF9FN -1Z9CCHOEVIyG0sXaWQE/QiLgNvDcq94KvSYrIhOHph8j7w6ZJ4sVShvvk8lrkd6g -Agxiu8xWN+glksMf8WnYfKgz4InOFGegOXeIkeajB5eQIojQeRhj+29+7itCfiP1 -59rp7mr6lmWf4SsVScjNLc6GTywqZ3m/QTAUzPYPFHSettPQO/AbuOgZKv3W/dxL -TmV9m783fi01Ii50kM5BNT1BoJnblx+/Phg8SPva38ZOTrlnuBDVpRMDxLdl56rw -FEvTTer+j2nPUCFjJ8+eTGcVez872ssXgGEeJQIDAQABAoIBAGQCMFW+ZfyEqHGP -rMA+oUEAkqy0agSwPwky3QjDXlxNa0uCYSeebtTRB6CcHxHuCzm+04puN4gyqhW6 -rU64fAoTivCMPGBuNWxekmvD9r+/YM4P2u4E+th9EgFT9f0kII+dO30FpKXtQzY0 -xuWGWXcxl+T9M+eiEkPKPmq4BoqgTDo5ty7qDv0ZqksGotKFmdYbtSvgBAueJdwu -VWJvenI9F42ExBRKOW1aldiRiaYBCLiCVPKJtOg9iuOP9RHUL1SE8xy5I5mm78g3 -a13ji3BNq3yS+VhGjQ7zDy1V1jGupLoJw4I7OThu8hy+B8Vt8EN/iqakufOkjlTN -xTJ33CkCgYEA5Iymg0NTjWk6aEkFa9pERjfUWqdVp9sWSpFFZZgi55n7LOx6ohi3 -vuLim3is/gYfK2kU/kHGZZLPnT0Rdx0MbOB4XK0CAUlqtUd0IyO4jMZ06g4/kn3N -e2jLdCCIBoEQuLk4ELxj2mHsLQhEvDrg7nzU2WpTHHhvJbIbDWOAxhsCgYEAzAgv -rKpanF+QDf4yeKHxAj2rrwRksTw4Pe7ZK/bog/i+HIVDA70vMapqftHbual/IRrB -JL7hxskoJ/h9c1w4xkWDjqkSKz8/Ihr4dyPfWyGINWbx/rarT/m5MU5SarScoK7o -Xgb25x+W+61rtI+2JhVRGO86+JiAeT4LkAX88L8CgYAwHHug/jdEeXZWJakCfzwI -HBCT1M3vO+uBXvtg25ndb0i0uENIhDOJ93EEkW65Osis9r34mBgPocwaqZRXosHO -2aH8wF6/rpjL+HK2QvrCh7Rs4Pr494qeA/1wQLjhxaGjgToQK9hJTHvPLwJpLWvU -SGr2Ka+9Oo0LPmb7dorRKQKBgQCLsNcjOodLJMp2KiHYIdfmlt6itzlRd09yZ8Nc -rHHJWVagJEUbnD1hnbHIHlp3pSqbObwfMmlWNoc9xo3tm6hrZ1CJLgx4e5b3/Ms8 -ltznge/F0DPDFsH3wZwfu+YFlJ7gDKCfL9l/qEsxCS0CtJobPOEHV1NivNbJK8ey -1ca19QKBgDTdMOUsobAmDEkPQIpxfK1iqYAB7hpRLi79OOhLp23NKeyRNu8FH9fo -G3DZ4xUi6hP2bwiYugMXDyLKfvxbsXwQC84kGF8j+bGazKNhHqEC1OpYwmaTB3kg -qL9cHbjWySeRdIsRY/eWmiKjUwmiO54eAe1HWUdcsuz8yM3xf636 ------END RSA PRIVATE KEY----- diff --git a/test/stress_tests/test_deleted_cert/test_restart_while_missing_cert.py b/test/stress_tests/test_deleted_cert/test_restart_while_missing_cert.py deleted file mode 100644 index d7e4cbbb5..000000000 --- a/test/stress_tests/test_deleted_cert/test_restart_while_missing_cert.py +++ /dev/null @@ -1,72 +0,0 @@ -import logging -import os -from os.path import join, isfile -from shutil import copy -from time import sleep - -import pytest -from requests import ConnectionError - -script_dir = os.path.dirname(__file__) - -pytestmark = pytest.mark.xfail() # TODO delete this marker once those issues are fixed - -@pytest.fixture(scope="module", autouse=True) -def certs(): - """ - pytest fixture that provides cert and key files into the tmp_certs directory - """ - file_names = ("web.nginx-proxy.crt", "web.nginx-proxy.key") - logging.info("copying server cert and key files into tmp_certs") - for f_name in file_names: - copy(join(script_dir, "certs", f_name), join(script_dir, "tmp_certs")) - yield - logging.info("cleaning up the tmp_cert directory") - for f_name in file_names: - if isfile(join(script_dir, "tmp_certs", f_name)): - os.remove(join(script_dir, "tmp_certs", f_name)) - -############################################################################### - - -def test_unknown_virtual_host_is_503(docker_compose, nginxproxy): - r = nginxproxy.get("http://foo.nginx-proxy/") - assert r.status_code == 503 - - -def test_http_web_is_301(docker_compose, nginxproxy): - r = nginxproxy.get("http://web.nginx-proxy/port", allow_redirects=False) - assert r.status_code == 301 - - -def test_https_web_is_200(docker_compose, nginxproxy): - r = nginxproxy.get("https://web.nginx-proxy/port") - assert r.status_code == 200 - assert "answer from port 81\n" in r.text - - -@pytest.mark.incremental -def test_delete_cert_and_restart_reverseproxy(docker_compose): - os.remove(join(script_dir, "tmp_certs", "web.nginx-proxy.crt")) - docker_compose.containers.get("reverseproxy").restart() - sleep(3) # give time for the container to initialize - assert "running" == docker_compose.containers.get("reverseproxy").status - - -@pytest.mark.incremental -def test_unknown_virtual_host_is_still_503(nginxproxy): - r = nginxproxy.get("http://foo.nginx-proxy/") - assert r.status_code == 503 - - -@pytest.mark.incremental -def test_http_web_is_now_200(nginxproxy): - r = nginxproxy.get("http://web.nginx-proxy/port", allow_redirects=False) - assert r.status_code == 200 - assert "answer from port 81\n" == r.text - - -@pytest.mark.incremental -def test_https_web_is_now_broken_since_there_is_no_cert(nginxproxy): - with pytest.raises(ConnectionError): - nginxproxy.get("https://web.nginx-proxy/port") diff --git a/test/stress_tests/test_deleted_cert/tmp_certs/.gitignore b/test/stress_tests/test_deleted_cert/tmp_certs/.gitignore deleted file mode 100644 index c96a04f00..000000000 --- a/test/stress_tests/test_deleted_cert/tmp_certs/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -* -!.gitignore \ No newline at end of file diff --git a/test/test_acme_http_challenge_location/acme_root/.well-known/acme-challenge/test-filename b/test/test_acme_http_challenge_location/acme_root/.well-known/acme-challenge/test-filename new file mode 100644 index 000000000..5b45dff28 --- /dev/null +++ b/test/test_acme_http_challenge_location/acme_root/.well-known/acme-challenge/test-filename @@ -0,0 +1 @@ +challenge-teststring diff --git a/test/test_acme_http_challenge_location/certs/nginx-proxy.tld.crt b/test/test_acme_http_challenge_location/certs/nginx-proxy.tld.crt new file mode 100644 index 000000000..cd7284b06 --- /dev/null +++ b/test/test_acme_http_challenge_location/certs/nginx-proxy.tld.crt @@ -0,0 +1,70 @@ +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 4096 (0x1000) + Signature Algorithm: sha256WithRSAEncryption + Issuer: O=nginx-proxy test suite, CN=www.nginx-proxy.tld + Validity + Not Before: Jan 10 00:08:52 2017 GMT + Not After : May 28 00:08:52 2044 GMT + Subject: CN=*.nginx-proxy.tld + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:cb:45:f4:14:9b:fe:64:85:79:4a:36:8d:3d:d1: + 27:d0:7c:36:28:30:e6:73:80:6f:7c:49:23:d0:6c: + 17:e4:44:c0:77:4d:9a:c2:bc:24:84:e3:a5:4d:ba: + d2:da:51:7b:a1:2a:12:d4:c0:19:55:69:2c:22:27: + 2d:1a:f6:fc:4b:7f:e9:cb:a8:3c:e8:69:b8:d2:4f: + de:4e:50:e2:d0:74:30:7c:42:5a:ae:aa:85:a5:b1: + 71:4d:c9:7e:86:8b:62:8c:3e:0d:e3:3b:c3:f5:81: + 0b:8c:68:79:fe:bf:10:fb:ae:ec:11:49:6d:64:5e: + 1a:7d:b3:92:93:4e:96:19:3a:98:04:a7:66:b2:74: + 61:2d:41:13:0c:a4:54:0d:2c:78:fd:b4:a3:e8:37: + 78:9a:de:fa:bc:2e:a8:0f:67:14:58:ce:c3:87:d5: + 14:0e:8b:29:7d:48:19:b2:a9:f5:b4:e8:af:32:21: + 67:15:7e:43:52:8b:20:cf:9f:38:43:bf:fd:c8:24: + 7f:52:a3:88:f2:f1:4a:14:91:2a:6e:91:6f:fb:7d: + 6a:78:c6:6d:2e:dd:1e:4c:2b:63:bb:3a:43:9c:91: + f9:df:d3:08:13:63:86:7d:ce:e8:46:cf:f1:6c:1f: + ca:f7:4c:de:d8:4b:e0:da:bc:06:d9:87:0f:ff:96: + 45:85 + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Subject Alternative Name: + DNS:*.nginx-proxy.tld + Signature Algorithm: sha256WithRSAEncryption + 6e:a5:0e:e4:d3:cc:d5:b7:fc:34:75:89:4e:98:8c:e7:08:06: + a8:5b:ec:13:7d:83:99:a2:61:b8:d5:12:6e:c5:b4:53:4e:9a: + 22:cd:ad:14:30:6a:7d:58:d7:23:d9:a4:2a:96:a0:40:9e:50: + 9f:ce:f2:fe:8c:dd:9a:ac:99:39:5b:89:2d:ca:e5:3e:c3:bc: + 03:04:1c:12:d9:6e:b8:9f:f0:3a:be:12:44:7e:a4:21:86:73: + af:d5:00:51:3f:2c:56:70:34:8f:26:b0:7f:b0:cf:cf:7f:f9: + 40:6f:00:29:c4:cf:c3:b7:c2:49:3d:3f:b0:26:78:87:b9:c7: + 6c:1b:aa:6a:1a:dd:c5:eb:f2:69:ba:6d:46:0b:92:49:b5:11: + 3c:eb:48:c7:2f:fb:33:a6:6a:82:a2:ab:f8:1e:5f:7d:e3:b7: + f2:fd:f5:88:a5:09:4d:a0:bc:f4:3b:cd:d2:8b:d7:57:1f:86: + 3b:d2:3e:a4:92:21:b0:02:0b:e9:e0:c4:1c:f1:78:e2:58:a7: + 26:5f:4c:29:c8:23:f0:6e:12:3f:bd:ad:44:7b:0b:bd:db:ba: + 63:8d:07:c6:9d:dc:46:cc:63:40:ba:5e:45:82:dd:9a:e5:50: + e8:e7:d7:27:88:fc:6f:1d:8a:e7:5c:49:28:aa:10:29:75:28: + c7:52:de:f9 +-----BEGIN CERTIFICATE----- +MIIC9zCCAd+gAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwPzEfMB0GA1UECgwWbmdp +bngtcHJveHkgdGVzdCBzdWl0ZTEcMBoGA1UEAwwTd3d3Lm5naW54LXByb3h5LnRs +ZDAeFw0xNzAxMTAwMDA4NTJaFw00NDA1MjgwMDA4NTJaMBwxGjAYBgNVBAMMESou +bmdpbngtcHJveHkudGxkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA +y0X0FJv+ZIV5SjaNPdEn0Hw2KDDmc4BvfEkj0GwX5ETAd02awrwkhOOlTbrS2lF7 +oSoS1MAZVWksIictGvb8S3/py6g86Gm40k/eTlDi0HQwfEJarqqFpbFxTcl+hoti +jD4N4zvD9YELjGh5/r8Q+67sEUltZF4afbOSk06WGTqYBKdmsnRhLUETDKRUDSx4 +/bSj6Dd4mt76vC6oD2cUWM7Dh9UUDospfUgZsqn1tOivMiFnFX5DUosgz584Q7/9 +yCR/UqOI8vFKFJEqbpFv+31qeMZtLt0eTCtjuzpDnJH539MIE2OGfc7oRs/xbB/K +90ze2Evg2rwG2YcP/5ZFhQIDAQABoyAwHjAcBgNVHREEFTATghEqLm5naW54LXBy +b3h5LnRsZDANBgkqhkiG9w0BAQsFAAOCAQEAbqUO5NPM1bf8NHWJTpiM5wgGqFvs +E32DmaJhuNUSbsW0U06aIs2tFDBqfVjXI9mkKpagQJ5Qn87y/ozdmqyZOVuJLcrl +PsO8AwQcEtluuJ/wOr4SRH6kIYZzr9UAUT8sVnA0jyawf7DPz3/5QG8AKcTPw7fC +ST0/sCZ4h7nHbBuqahrdxevyabptRguSSbURPOtIxy/7M6ZqgqKr+B5ffeO38v31 +iKUJTaC89DvN0ovXVx+GO9I+pJIhsAIL6eDEHPF44linJl9MKcgj8G4SP72tRHsL +vdu6Y40Hxp3cRsxjQLpeRYLdmuVQ6OfXJ4j8bx2K51xJKKoQKXUox1Le+Q== +-----END CERTIFICATE----- diff --git a/test/test_acme_http_challenge_location/certs/nginx-proxy.tld.key b/test/test_acme_http_challenge_location/certs/nginx-proxy.tld.key new file mode 100644 index 000000000..91adb14e1 --- /dev/null +++ b/test/test_acme_http_challenge_location/certs/nginx-proxy.tld.key @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEAy0X0FJv+ZIV5SjaNPdEn0Hw2KDDmc4BvfEkj0GwX5ETAd02a +wrwkhOOlTbrS2lF7oSoS1MAZVWksIictGvb8S3/py6g86Gm40k/eTlDi0HQwfEJa +rqqFpbFxTcl+hotijD4N4zvD9YELjGh5/r8Q+67sEUltZF4afbOSk06WGTqYBKdm +snRhLUETDKRUDSx4/bSj6Dd4mt76vC6oD2cUWM7Dh9UUDospfUgZsqn1tOivMiFn +FX5DUosgz584Q7/9yCR/UqOI8vFKFJEqbpFv+31qeMZtLt0eTCtjuzpDnJH539MI +E2OGfc7oRs/xbB/K90ze2Evg2rwG2YcP/5ZFhQIDAQABAoIBAQCjAro2PNLJMfCO +fyjNRgmzu6iCmpR0U68T8GN0JPsT576g7e8J828l0pkhuIyW33lRSThIvLSUNf9a +dChL032H3lBTLduKVh4NKleQXnVFzaeEPoISSFVdButiAhAhPW4OIUVp0OfY3V+x +fac3j2nDLAfL5SKAtqZv363Py9m66EBYm5BmGTQqT/frQWeCEBvlErQef5RIaU8p +e2zMWgSNNojVai8U3nKNRvYHWeWXM6Ck7lCvkHhMF+RpbmCZuqhbEARVnehU/Jdn +QHJ3nxeA2OWpoWKXvAHtSnno49yxq1UIstiQvY+ng5C5i56UlB60UiU2NJ6doZkB +uQ7/1MaBAoGBAORdcFtgdgRALjXngFWhpCp0CseyUehn1KhxDCG+D1pJ142/ymcf +oJOzKJPMRNDdDUBMnR1GBfy7rmwvYevI/SMNy2Qs7ofcXPbdtwwvTCToZ1V9/54k +VfuPBFT+3QzWRvG1tjTV3E4L2VV3nrl2qNPhE5DlfIaU3nQq5Fl0HprJAoGBAOPf +MWOTGev61CdODO5KN3pLAoamiPs5lEUlz3kM3L1Q52YLITxNDjRj9hWBUATJZOS2 +pLOoYRwmhD7vrnimMc41+NuuFX+4T7hWPc8uSuOxX0VijYtULyNRK57mncG1Fq9M +RMLbOJ7FD+8jdXNsSMqpQ+pxLJRX/A10O2fOQnbdAoGAL5hV4YWSM0KZHvz332EI +ER0MXiCJN7HkPZMKH0I4eu3m8hEmAyYxVndBnsQ1F37q0xrkqAQ/HTSUntGlS/og +4Bxw5pkCwegoq/77tpto+ExDtSrEitYx4XMmSPyxX4qNULU5m3tzJgUML+b1etwD +Rd2kMU/TC02dq4KBAy/TbRkCgYAl1xN5iJz+XenLGR/2liZ+TWR+/bqzlU006mF4 +pZUmbv/uJxz+yYD5XDwqOA4UrWjuvhG9r9FoflDprp2XdWnB556KxG7XhcDfSJr9 +A5/2DadXe1Ur9O/a+oi2228JEsxQkea9QPA3FVxfBtFjOHEiDlez39VaUP4PMeUH +iO3qlQKBgFQhdTb7HeYnApYIDHLmd1PvjRvp8XKR1CpEN0nkw8HpHcT1q1MUjQCr +iT6FQupULEvGmO3frQsgVeRIQDbEdZK3C5xCtn6qOw70sYATVf361BbTtidmU9yV +THFxwDSVLiVZgFryoY/NtAc27sVdJnGsPRjjaeVgALAsLbmZ1K/H +-----END RSA PRIVATE KEY----- diff --git a/test/test_acme_http_challenge_location/test_acme_challenge_location_disabled.py b/test/test_acme_http_challenge_location/test_acme_challenge_location_disabled.py new file mode 100644 index 000000000..acbc8feb9 --- /dev/null +++ b/test/test_acme_http_challenge_location/test_acme_challenge_location_disabled.py @@ -0,0 +1,30 @@ +import pytest + + +def test_redirect_acme_challenge_location_disabled(docker_compose, nginxproxy, acme_challenge_path): + r = nginxproxy.get( + f"http://web1.nginx-proxy.tld/{acme_challenge_path}", + allow_redirects=False + ) + assert r.status_code == 301 + +def test_redirect_acme_challenge_location_enabled(docker_compose, nginxproxy, acme_challenge_path): + r = nginxproxy.get( + f"http://web2.nginx-proxy.tld/{acme_challenge_path}", + allow_redirects=False + ) + assert r.status_code == 200 + +def test_noredirect_acme_challenge_location_disabled(docker_compose, nginxproxy, acme_challenge_path): + r = nginxproxy.get( + f"http://web3.nginx-proxy.tld/{acme_challenge_path}", + allow_redirects=False + ) + assert r.status_code == 404 + +def test_noredirect_acme_challenge_location_enabled(docker_compose, nginxproxy, acme_challenge_path): + r = nginxproxy.get( + f"http://web4.nginx-proxy.tld/{acme_challenge_path}", + allow_redirects=False + ) + assert r.status_code == 200 diff --git a/test/test_acme_http_challenge_location/test_acme_challenge_location_disabled.yml b/test/test_acme_http_challenge_location/test_acme_challenge_location_disabled.yml new file mode 100644 index 000000000..3cd4f2d62 --- /dev/null +++ b/test/test_acme_http_challenge_location/test_acme_challenge_location_disabled.yml @@ -0,0 +1,47 @@ +version: "2" + +services: + web1: + image: web + expose: + - "81" + environment: + WEB_PORTS: "81" + VIRTUAL_HOST: "web1.nginx-proxy.tld" + + web2: + image: web + expose: + - "82" + environment: + WEB_PORTS: "82" + VIRTUAL_HOST: "web2.nginx-proxy.tld" + ACME_HTTP_CHALLENGE_LOCATION: "true" + + web3: + image: web + expose: + - "83" + environment: + WEB_PORTS: "83" + VIRTUAL_HOST: "web3.nginx-proxy.tld" + HTTPS_METHOD: noredirect + + web4: + image: web + expose: + - "84" + environment: + WEB_PORTS: "84" + VIRTUAL_HOST: "web4.nginx-proxy.tld" + HTTPS_METHOD: noredirect + ACME_HTTP_CHALLENGE_LOCATION: "true" + + sut: + image: nginxproxy/nginx-proxy:test + environment: + ACME_HTTP_CHALLENGE_LOCATION: "false" + volumes: + - /var/run/docker.sock:/tmp/docker.sock:ro + - ./certs:/etc/nginx/certs:ro + - ./acme_root:/usr/share/nginx/html:ro diff --git a/test/test_acme_http_challenge_location/test_acme_challenge_location_enabled_is_default.py b/test/test_acme_http_challenge_location/test_acme_challenge_location_enabled_is_default.py new file mode 100644 index 000000000..fd06e847d --- /dev/null +++ b/test/test_acme_http_challenge_location/test_acme_challenge_location_enabled_is_default.py @@ -0,0 +1,30 @@ +import pytest + + +def test_redirect_acme_challenge_location_enabled(docker_compose, nginxproxy, acme_challenge_path): + r = nginxproxy.get( + f"http://web1.nginx-proxy.tld/{acme_challenge_path}", + allow_redirects=False + ) + assert r.status_code == 200 + +def test_redirect_acme_challenge_location_disabled(docker_compose, nginxproxy, acme_challenge_path): + r = nginxproxy.get( + f"http://web2.nginx-proxy.tld/{acme_challenge_path}", + allow_redirects=False + ) + assert r.status_code == 301 + +def test_noredirect_acme_challenge_location_enabled(docker_compose, nginxproxy, acme_challenge_path): + r = nginxproxy.get( + f"http://web3.nginx-proxy.tld/{acme_challenge_path}", + allow_redirects=False + ) + assert r.status_code == 200 + +def test_noredirect_acme_challenge_location_disabled(docker_compose, nginxproxy, acme_challenge_path): + r = nginxproxy.get( + f"http://web4.nginx-proxy.tld/{acme_challenge_path}", + allow_redirects=False + ) + assert r.status_code == 404 diff --git a/test/test_acme_http_challenge_location/test_acme_challenge_location_enabled_is_default.yml b/test/test_acme_http_challenge_location/test_acme_challenge_location_enabled_is_default.yml new file mode 100644 index 000000000..41439e30c --- /dev/null +++ b/test/test_acme_http_challenge_location/test_acme_challenge_location_enabled_is_default.yml @@ -0,0 +1,45 @@ +version: "2" + +services: + web1: + image: web + expose: + - "81" + environment: + WEB_PORTS: "81" + VIRTUAL_HOST: "web1.nginx-proxy.tld" + + web2: + image: web + expose: + - "82" + environment: + WEB_PORTS: "82" + VIRTUAL_HOST: "web2.nginx-proxy.tld" + ACME_HTTP_CHALLENGE_LOCATION: "false" + + web3: + image: web + expose: + - "83" + environment: + WEB_PORTS: "83" + VIRTUAL_HOST: "web3.nginx-proxy.tld" + HTTPS_METHOD: noredirect + + web4: + image: web + expose: + - "84" + environment: + WEB_PORTS: "84" + VIRTUAL_HOST: "web4.nginx-proxy.tld" + HTTPS_METHOD: noredirect + ACME_HTTP_CHALLENGE_LOCATION: "false" + + sut: + image: nginxproxy/nginx-proxy:test + volumes: + - /var/run/docker.sock:/tmp/docker.sock:ro + - ./certs:/etc/nginx/certs:ro + - ./acme_root:/usr/share/nginx/html:ro diff --git a/test/test_acme_http_challenge_location/test_acme_challenge_location_legacy.py b/test/test_acme_http_challenge_location/test_acme_challenge_location_legacy.py new file mode 100644 index 000000000..d2051d0aa --- /dev/null +++ b/test/test_acme_http_challenge_location/test_acme_challenge_location_legacy.py @@ -0,0 +1,16 @@ +import pytest + + +def test_redirect_acme_challenge_location_legacy(docker_compose, nginxproxy, acme_challenge_path): + r = nginxproxy.get( + f"http://web1.nginx-proxy.tld/{acme_challenge_path}", + allow_redirects=False + ) + assert r.status_code == 200 + +def test_noredirect_acme_challenge_location_legacy(docker_compose, nginxproxy, acme_challenge_path): + r = nginxproxy.get( + f"http://web2.nginx-proxy.tld/{acme_challenge_path}", + allow_redirects=False + ) + assert r.status_code == 404 diff --git a/test/test_acme_http_challenge_location/test_acme_challenge_location_legacy.yml b/test/test_acme_http_challenge_location/test_acme_challenge_location_legacy.yml new file mode 100644 index 000000000..693f9e013 --- /dev/null +++ b/test/test_acme_http_challenge_location/test_acme_challenge_location_legacy.yml @@ -0,0 +1,28 @@ +version: "2" + +services: + web1: + image: web + expose: + - "81" + environment: + WEB_PORTS: "81" + VIRTUAL_HOST: "web1.nginx-proxy.tld" + + web2: + image: web + expose: + - "82" + environment: + WEB_PORTS: "82" + VIRTUAL_HOST: "web2.nginx-proxy.tld" + HTTPS_METHOD: noredirect + + sut: + image: nginxproxy/nginx-proxy:test + environment: + ACME_HTTP_CHALLENGE_LOCATION: "legacy" + volumes: + - /var/run/docker.sock:/tmp/docker.sock:ro + - ./certs:/etc/nginx/certs:ro + - ./acme_root:/usr/share/nginx/html:ro diff --git a/test/test_build.py b/test/test_build.py new file mode 100644 index 000000000..4052d1ee0 --- /dev/null +++ b/test/test_build.py @@ -0,0 +1,63 @@ +""" +Test that nginx-proxy-tester can build successfully +""" +import pytest +import docker +import re +import os + +client = docker.from_env() + +@pytest.fixture(scope = "session") +def docker_build(request): + # Define Dockerfile path + dockerfile_path = os.path.join(os.path.dirname(__file__), "requirements/") + dockerfile_name = "Dockerfile-nginx-proxy-tester" + + # Build the Docker image + image, logs = client.images.build( + path = dockerfile_path, + dockerfile = dockerfile_name, + rm = True, # Remove intermediate containers + tag = "nginx-proxy-tester-ci", # Tag for the built image + ) + + # Check for build success + for log in logs: + if "stream" in log: + print(log["stream"].strip()) + if "error" in log: + raise Exception(log["error"]) + + def teardown(): + # Clean up after teardown + client.images.remove(image.id, force=True) + + request.addfinalizer(teardown) + + # Return the image name + return "nginx-proxy-tester-ci" + +def test_build_nginx_proxy_tester(docker_build): + assert docker_build == "nginx-proxy-tester-ci" + +def test_run_nginx_proxy_tester(docker_build): + # Run the container with 'pytest -v' command to output version info + container = client.containers.run("nginx-proxy-tester-ci", + command = "pytest -V", + detach = True, + ) + + # Wait for the container to finish and get the exit code + result = container.wait() + exit_code = result.get("StatusCode", 1) # Default to 1 (error) if not found + + # Get the output logs from the container + output = container.logs().decode("utf-8").strip() + + # Clean up: Remove the container + container.remove() + + # Assertions + assert exit_code == 0, "Container exited with a non-zero exit code" + assert re.search(r"pytest\s\d+\.\d+\.\d+", output) diff --git a/test/test_composev2.py b/test/test_composev2.py deleted file mode 100644 index 695857efe..000000000 --- a/test/test_composev2.py +++ /dev/null @@ -1,10 +0,0 @@ -import pytest - -def test_unknown_virtual_host(docker_compose, nginxproxy): - r = nginxproxy.get("http://nginx-proxy/") - assert r.status_code == 503 - -def test_forwards_to_whoami(docker_compose, nginxproxy): - r = nginxproxy.get("http://web.nginx-proxy.example/port") - assert r.status_code == 200 - assert r.text == "answer from port 81\n" diff --git a/test/test_custom-error-page/50x.html b/test/test_custom-error-page/50x.html new file mode 100644 index 000000000..63a299ec0 --- /dev/null +++ b/test/test_custom-error-page/50x.html @@ -0,0 +1,23 @@ + + + + Maintenance + + + +

Damn, there's some maintenance in progress.

+

+ Our apologies for this temporary inconvenience. Regular service + performance will be re-established shortly. +

+ + diff --git a/test/test_custom-error-page/test_custom-error-page.py b/test/test_custom-error-page/test_custom-error-page.py new file mode 100644 index 000000000..32cb0b542 --- /dev/null +++ b/test/test_custom-error-page/test_custom-error-page.py @@ -0,0 +1,8 @@ +import pytest +import re + + +def test_custom_error_page(docker_compose, nginxproxy): + r = nginxproxy.get("http://unknown.nginx-proxy.tld") + assert r.status_code == 503 + assert re.search(r"Damn, there's some maintenance in progress.", r.text) diff --git a/test/test_custom-error-page/test_custom-error-page.yml b/test/test_custom-error-page/test_custom-error-page.yml new file mode 100644 index 000000000..419b7eb8d --- /dev/null +++ b/test/test_custom-error-page/test_custom-error-page.yml @@ -0,0 +1,8 @@ +version: "2" + +services: + sut: + image: nginxproxy/nginx-proxy:test + volumes: + - /var/run/docker.sock:/tmp/docker.sock:ro + - ./50x.html:/usr/share/nginx/html/errors/50x.html:ro diff --git a/test/test_custom/my_custom_proxy_settings.conf b/test/test_custom/my_custom_proxy_settings_f00.conf similarity index 100% rename from test/test_custom/my_custom_proxy_settings.conf rename to test/test_custom/my_custom_proxy_settings_f00.conf diff --git a/test/test_custom/test_defaults-location.yml b/test/test_custom/test_defaults-location.yml index 9a3ab44f3..6e8965057 100644 --- a/test/test_custom/test_defaults-location.yml +++ b/test/test_custom/test_defaults-location.yml @@ -5,7 +5,7 @@ services: image: nginxproxy/nginx-proxy:test volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - - ./my_custom_proxy_settings.conf:/etc/nginx/vhost.d/default_location:ro + - ./my_custom_proxy_settings_f00.conf:/etc/nginx/vhost.d/default_location:ro - ./my_custom_proxy_settings_bar.conf:/etc/nginx/vhost.d/web3.nginx-proxy.example_location:ro web1: diff --git a/test/test_custom/test_defaults.yml b/test/test_custom/test_defaults.yml index d6a959a48..2f25387ba 100644 --- a/test/test_custom/test_defaults.yml +++ b/test/test_custom/test_defaults.yml @@ -5,7 +5,7 @@ services: image: nginxproxy/nginx-proxy:test volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - - ./my_custom_proxy_settings.conf:/etc/nginx/proxy.conf:ro + - ./my_custom_proxy_settings_f00.conf:/etc/nginx/proxy.conf:ro web1: image: web diff --git a/test/test_custom/test_location-per-vhost.py b/test/test_custom/test_location-per-vhost.py index 53a146b55..8218ed073 100644 --- a/test/test_custom/test_location-per-vhost.py +++ b/test/test_custom/test_location-per-vhost.py @@ -12,6 +12,13 @@ def test_custom_conf_applies_to_web1(docker_compose, nginxproxy): assert "X-test" in r.headers assert "f00" == r.headers["X-test"] +def test_custom_conf_applies_to_regex(docker_compose, nginxproxy): + r = nginxproxy.get("http://regex.foo.nginx-proxy.example/port") + assert r.status_code == 200 + assert r.text == "answer from port 83\n" + assert "X-test" in r.headers + assert "bar" == r.headers["X-test"] + def test_custom_conf_does_not_apply_to_web2(docker_compose, nginxproxy): r = nginxproxy.get("http://web2.nginx-proxy.example/port") assert r.status_code == 200 diff --git a/test/test_custom/test_location-per-vhost.yml b/test/test_custom/test_location-per-vhost.yml index 52943086e..71e606ab4 100644 --- a/test/test_custom/test_location-per-vhost.yml +++ b/test/test_custom/test_location-per-vhost.yml @@ -5,7 +5,8 @@ services: image: nginxproxy/nginx-proxy:test volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - - ./my_custom_proxy_settings.conf:/etc/nginx/vhost.d/web1.nginx-proxy.example_location:ro + - ./my_custom_proxy_settings_f00.conf:/etc/nginx/vhost.d/web1.nginx-proxy.example_location:ro + - ./my_custom_proxy_settings_bar.conf:/etc/nginx/vhost.d/561032515ede3ab3a015edfb244608b72409c430_location:ro web1: image: web @@ -22,3 +23,11 @@ services: environment: WEB_PORTS: 82 VIRTUAL_HOST: web2.nginx-proxy.example + + regex: + image: web + expose: + - "83" + environment: + WEB_PORTS: 83 + VIRTUAL_HOST: ~^regex.*\.nginx-proxy\.example$ diff --git a/test/test_custom/test_per-vhost.py b/test/test_custom/test_per-vhost.py index 6a85e6948..7394472d2 100644 --- a/test/test_custom/test_per-vhost.py +++ b/test/test_custom/test_per-vhost.py @@ -12,6 +12,13 @@ def test_custom_conf_applies_to_web1(docker_compose, nginxproxy): assert "X-test" in r.headers assert "f00" == r.headers["X-test"] +def test_custom_conf_applies_to_regex(docker_compose, nginxproxy): + r = nginxproxy.get("http://regex.foo.nginx-proxy.example/port") + assert r.status_code == 200 + assert r.text == "answer from port 83\n" + assert "X-test" in r.headers + assert "bar" == r.headers["X-test"] + def test_custom_conf_does_not_apply_to_web2(docker_compose, nginxproxy): r = nginxproxy.get("http://web2.nginx-proxy.example/port") assert r.status_code == 200 diff --git a/test/test_custom/test_per-vhost.yml b/test/test_custom/test_per-vhost.yml index 63d33b2b1..0795cef17 100644 --- a/test/test_custom/test_per-vhost.yml +++ b/test/test_custom/test_per-vhost.yml @@ -5,7 +5,8 @@ services: image: nginxproxy/nginx-proxy:test volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - - ./my_custom_proxy_settings.conf:/etc/nginx/vhost.d/web1.nginx-proxy.example:ro + - ./my_custom_proxy_settings_f00.conf:/etc/nginx/vhost.d/web1.nginx-proxy.example:ro + - ./my_custom_proxy_settings_bar.conf:/etc/nginx/vhost.d/561032515ede3ab3a015edfb244608b72409c430:ro web1: image: web @@ -22,3 +23,11 @@ services: environment: WEB_PORTS: 82 VIRTUAL_HOST: web2.nginx-proxy.example + + regex: + image: web + expose: + - "83" + environment: + WEB_PORTS: 83 + VIRTUAL_HOST: ~^regex.*\.nginx-proxy\.example$ diff --git a/test/test_custom/test_proxy-wide.yml b/test/test_custom/test_proxy-wide.yml index 1322bcde7..22e5c1857 100644 --- a/test/test_custom/test_proxy-wide.yml +++ b/test/test_custom/test_proxy-wide.yml @@ -5,7 +5,7 @@ services: image: nginxproxy/nginx-proxy:test volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - - ./my_custom_proxy_settings.conf:/etc/nginx/conf.d/my_custom_proxy_settings.conf:ro + - ./my_custom_proxy_settings_f00.conf:/etc/nginx/conf.d/my_custom_proxy_settings_f00.conf:ro web1: image: web diff --git a/test/test_debug_endpoint/test_global.py b/test/test_debug_endpoint/test_global.py new file mode 100644 index 000000000..aaa7b1fc0 --- /dev/null +++ b/test/test_debug_endpoint/test_global.py @@ -0,0 +1,46 @@ +import json +import pytest + +def test_debug_endpoint_is_enabled_globally(docker_compose, nginxproxy): + r = nginxproxy.get("http://enabled.debug.nginx-proxy.example/nginx-proxy-debug") + assert r.status_code == 200 + r = nginxproxy.get("http://stripped.debug.nginx-proxy.example/nginx-proxy-debug") + assert r.status_code == 200 + + +def test_debug_endpoint_response_contains_expected_values(docker_compose, nginxproxy): + r = nginxproxy.get("http://enabled.debug.nginx-proxy.example/nginx-proxy-debug") + assert r.status_code == 200 + try: + jsonResponse = json.loads(r.text) + except ValueError as err: + pytest.fail("Failed to parse debug endpoint response as JSON: %s" % err, pytrace=False) + assert jsonResponse["global"]["enable_debug_endpoint"] == "true" + assert jsonResponse["vhost"]["enable_debug_endpoint"] == True + + +def test_debug_endpoint_paths_stripped_if_response_too_long(docker_compose, nginxproxy): + r = nginxproxy.get("http://stripped.debug.nginx-proxy.example/nginx-proxy-debug") + assert r.status_code == 200 + try: + jsonResponse = json.loads(r.text) + except ValueError as err: + pytest.fail("Failed to parse debug endpoint response as JSON: %s" % err, pytrace=False) + if "paths" in jsonResponse["vhost"]: + pytest.fail("Expected paths to be stripped from debug endpoint response", pytrace=False) + assert jsonResponse["warning"] == "Virtual paths configuration for this hostname is too large and has been stripped from response." + + +def test_debug_endpoint_hostname_replaced_by_warning_if_regexp(docker_compose, nginxproxy): + r = nginxproxy.get("http://regexp.foo.debug.nginx-proxy.example/nginx-proxy-debug") + assert r.status_code == 200 + try: + jsonResponse = json.loads(r.text) + except ValueError as err: + pytest.fail("Failed to parse debug endpoint response as JSON: %s" % err, pytrace=False) + assert jsonResponse["vhost"]["hostname"] == "Hostname is a regexp and unsafe to include in the debug response." + + +def test_debug_endpoint_is_disabled_per_container(docker_compose, nginxproxy): + r = nginxproxy.get("http://disabled.debug.nginx-proxy.example/nginx-proxy-debug") + assert r.status_code == 404 diff --git a/test/test_debug_endpoint/test_global.yml b/test/test_debug_endpoint/test_global.yml new file mode 100644 index 000000000..179703899 --- /dev/null +++ b/test/test_debug_endpoint/test_global.yml @@ -0,0 +1,62 @@ +services: + nginx-proxy: + image: nginxproxy/nginx-proxy:test + volumes: + - /var/run/docker.sock:/tmp/docker.sock:ro + environment: + DEBUG_ENDPOINT: "true" + + debug_enabled: + image: web + expose: + - "81" + environment: + WEB_PORTS: 81 + VIRTUAL_HOST: enabled.debug.nginx-proxy.example + + debug_stripped: + image: web + expose: + - "82" + environment: + WEB_PORTS: 82 + VIRTUAL_HOST_MULTIPORTS: |- + stripped.debug.nginx-proxy.example: + "/1": + "/2": + "/3": + "/4": + "/5": + "/6": + "/7": + "/8": + "/9": + "/10": + "/11": + "/12": + "/13": + "/14": + "/15": + "/16": + "/17": + "/18": + "/19": + "/20": + + debug_regexp: + image: web + expose: + - "84" + environment: + WEB_PORTS: 84 + VIRTUAL_HOST: ~^regexp.*\.debug.nginx-proxy.example + + debug_disabled: + image: web + expose: + - "83" + environment: + WEB_PORTS: 83 + VIRTUAL_HOST: disabled.debug.nginx-proxy.example + labels: + com.github.nginx-proxy.nginx-proxy.debug-endpoint: "false" diff --git a/test/test_debug_endpoint/test_per_container.py b/test/test_debug_endpoint/test_per_container.py new file mode 100644 index 000000000..16c680c33 --- /dev/null +++ b/test/test_debug_endpoint/test_per_container.py @@ -0,0 +1,24 @@ +import json +import pytest + +def test_debug_endpoint_is_disabled_globally(docker_compose, nginxproxy): + r = nginxproxy.get("http://disabled1.debug.nginx-proxy.example/nginx-proxy-debug") + assert r.status_code == 404 + r = nginxproxy.get("http://disabled2.debug.nginx-proxy.example/nginx-proxy-debug") + assert r.status_code == 404 + + +def test_debug_endpoint_is_enabled_per_container(docker_compose, nginxproxy): + r = nginxproxy.get("http://enabled.debug.nginx-proxy.example/nginx-proxy-debug") + assert r.status_code == 200 + + +def test_debug_endpoint_response_contains_expected_values(docker_compose, nginxproxy): + r = nginxproxy.get("http://enabled.debug.nginx-proxy.example/nginx-proxy-debug") + assert r.status_code == 200 + try: + jsonResponse = json.loads(r.text) + except ValueError as err: + pytest.fail("Failed to parse debug endpoint response as JSON:: %s" % err, pytrace=False) + assert jsonResponse["global"]["enable_debug_endpoint"] == "false" + assert jsonResponse["vhost"]["enable_debug_endpoint"] == True diff --git a/test/test_debug_endpoint/test_per_container.yml b/test/test_debug_endpoint/test_per_container.yml new file mode 100644 index 000000000..56c975cfe --- /dev/null +++ b/test/test_debug_endpoint/test_per_container.yml @@ -0,0 +1,32 @@ +services: + nginx-proxy: + image: nginxproxy/nginx-proxy:test + volumes: + - /var/run/docker.sock:/tmp/docker.sock:ro + + debug_disabled1: + image: web + expose: + - "81" + environment: + WEB_PORTS: 81 + VIRTUAL_HOST: disabled1.debug.nginx-proxy.example + + debug_disabled2: + image: web + expose: + - "82" + environment: + WEB_PORTS: 82 + VIRTUAL_HOST: disabled2.debug.nginx-proxy.example + + + debug_enabled: + image: web + expose: + - "83" + environment: + WEB_PORTS: 83 + VIRTUAL_HOST: enabled.debug.nginx-proxy.example + labels: + com.github.nginx-proxy.nginx-proxy.debug-endpoint: "true" diff --git a/test/test_enable_http_on_missing_cert.py b/test/test_enable_http_on_missing_cert.py new file mode 100644 index 000000000..cdedc8a2c --- /dev/null +++ b/test/test_enable_http_on_missing_cert.py @@ -0,0 +1,18 @@ +import pytest + + +def test_nohttp_missing_cert_disabled(docker_compose, nginxproxy): + r = nginxproxy.get("http://nohttp-missing-cert-disabled.nginx-proxy.tld/", allow_redirects=False) + assert r.status_code == 503 + +def test_nohttp_missing_cert_enabled(docker_compose, nginxproxy): + r = nginxproxy.get("http://nohttp-missing-cert-enabled.nginx-proxy.tld/", allow_redirects=False) + assert r.status_code == 200 + +def test_redirect_missing_cert_disabled(docker_compose, nginxproxy): + r = nginxproxy.get("http://redirect-missing-cert-disabled.nginx-proxy.tld/", allow_redirects=False) + assert r.status_code == 301 + +def test_redirect_missing_cert_enabled(docker_compose, nginxproxy): + r = nginxproxy.get("http://redirect-missing-cert-enabled.nginx-proxy.tld/", allow_redirects=False) + assert r.status_code == 200 diff --git a/test/test_enable_http_on_missing_cert.yml b/test/test_enable_http_on_missing_cert.yml new file mode 100644 index 000000000..1149ef720 --- /dev/null +++ b/test/test_enable_http_on_missing_cert.yml @@ -0,0 +1,46 @@ +version: "2" + +services: + sut: + image: nginxproxy/nginx-proxy:test + volumes: + - /var/run/docker.sock:/tmp/docker.sock:ro + - ./withdefault.certs:/etc/nginx/certs:ro + environment: + ENABLE_HTTP_ON_MISSING_CERT: "false" + + nohttp-missing-cert-disabled: + image: web + expose: + - "81" + environment: + WEB_PORTS: "81" + VIRTUAL_HOST: nohttp-missing-cert-disabled.nginx-proxy.tld + HTTPS_METHOD: nohttp + + nohttp-missing-cert-enabled: + image: web + expose: + - "82" + environment: + WEB_PORTS: "82" + VIRTUAL_HOST: nohttp-missing-cert-enabled.nginx-proxy.tld + HTTPS_METHOD: nohttp + ENABLE_HTTP_ON_MISSING_CERT: "true" + + redirect-missing-cert-disabled: + image: web + expose: + - "83" + environment: + WEB_PORTS: "83" + VIRTUAL_HOST: redirect-missing-cert-disabled.nginx-proxy.tld + + redirect-missing-cert-enabled: + image: web + expose: + - "84" + environment: + WEB_PORTS: "84" + VIRTUAL_HOST: redirect-missing-cert-enabled.nginx-proxy.tld + ENABLE_HTTP_ON_MISSING_CERT: "true" diff --git a/test/test_fallback.py b/test/test_fallback.py index 1ee923ac1..a8a673aaa 100644 --- a/test/test_fallback.py +++ b/test/test_fallback.py @@ -21,7 +21,7 @@ def get(docker_compose, nginxproxy, want_err_re): @backoff.on_exception( backoff.constant, - requests.exceptions.RequestException, + requests.exceptions.SSLError, giveup=lambda e: want_err_re and want_err_re.search(str(e)), interval=.3, max_tries=30, @@ -32,8 +32,7 @@ def _get(url): return _get -INTERNAL_ERR_RE = re.compile("TLSV1_ALERT_INTERNAL_ERROR") -CONNECTION_REFUSED_RE = re.compile("Connection refused") +INTERNAL_ERR_RE = re.compile("TLSV1_UNRECOGNIZED_NAME") @pytest.mark.parametrize("compose_file,url,want_code,want_err_re", [ @@ -60,19 +59,17 @@ def _get(url): ("nodefault.yml", "http://unknown.nginx-proxy.test/", 503, None), ("nodefault.yml", "https://unknown.nginx-proxy.test/", None, INTERNAL_ERR_RE), # HTTPS_METHOD=nohttp on nginx-proxy, HTTPS_METHOD unset on the app container. - ("nohttp.yml", "http://https-only.nginx-proxy.test/", None, CONNECTION_REFUSED_RE), + ("nohttp.yml", "http://https-only.nginx-proxy.test/", 503, None), ("nohttp.yml", "https://https-only.nginx-proxy.test/", 200, None), - ("nohttp.yml", "http://unknown.nginx-proxy.test/", None, CONNECTION_REFUSED_RE), + ("nohttp.yml", "http://unknown.nginx-proxy.test/", 503, None), ("nohttp.yml", "https://unknown.nginx-proxy.test/", 503, None), # HTTPS_METHOD=redirect on nginx-proxy, HTTPS_METHOD=nohttp on the app container. - ("nohttp-on-app.yml", "http://https-only.nginx-proxy.test/", None, CONNECTION_REFUSED_RE), + ("nohttp-on-app.yml", "http://https-only.nginx-proxy.test/", 503, None), ("nohttp-on-app.yml", "https://https-only.nginx-proxy.test/", 200, None), - ("nohttp-on-app.yml", "http://unknown.nginx-proxy.test/", None, CONNECTION_REFUSED_RE), + ("nohttp-on-app.yml", "http://unknown.nginx-proxy.test/", 503, None), ("nohttp-on-app.yml", "https://unknown.nginx-proxy.test/", 503, None), # Same as nohttp.yml, except there is a vhost with a missing cert. This causes its - # HTTPS_METHOD=nohttp setting to effectively become HTTPS_METHOD=noredirect. This means that - # there will be a plain http server solely to support that vhost, so http requests to other - # vhosts get a 503, not a connection refused error. + # HTTPS_METHOD=nohttp setting to effectively become HTTPS_METHOD=noredirect. ("nohttp-with-missing-cert.yml", "http://https-only.nginx-proxy.test/", 503, None), ("nohttp-with-missing-cert.yml", "https://https-only.nginx-proxy.test/", 200, None), ("nohttp-with-missing-cert.yml", "http://missing-cert.nginx-proxy.test/", 200, None), @@ -81,14 +78,14 @@ def _get(url): ("nohttp-with-missing-cert.yml", "https://unknown.nginx-proxy.test/", 503, None), # HTTPS_METHOD=nohttps on nginx-proxy, HTTPS_METHOD unset on the app container. ("nohttps.yml", "http://http-only.nginx-proxy.test/", 200, None), - ("nohttps.yml", "https://http-only.nginx-proxy.test/", None, CONNECTION_REFUSED_RE), + ("nohttps.yml", "https://http-only.nginx-proxy.test/", None, INTERNAL_ERR_RE), ("nohttps.yml", "http://unknown.nginx-proxy.test/", 503, None), - ("nohttps.yml", "https://unknown.nginx-proxy.test/", None, CONNECTION_REFUSED_RE), + ("nohttps.yml", "https://unknown.nginx-proxy.test/", None, INTERNAL_ERR_RE), # HTTPS_METHOD=redirect on nginx-proxy, HTTPS_METHOD=nohttps on the app container. ("nohttps-on-app.yml", "http://http-only.nginx-proxy.test/", 200, None), - ("nohttps-on-app.yml", "https://http-only.nginx-proxy.test/", None, CONNECTION_REFUSED_RE), + ("nohttps-on-app.yml", "https://http-only.nginx-proxy.test/", None, INTERNAL_ERR_RE), ("nohttps-on-app.yml", "http://unknown.nginx-proxy.test/", 503, None), - ("nohttps-on-app.yml", "https://unknown.nginx-proxy.test/", None, CONNECTION_REFUSED_RE), + ("nohttps-on-app.yml", "https://unknown.nginx-proxy.test/", None, INTERNAL_ERR_RE), # Custom nginx config that has a `server` directive that uses `default_server` and simply # returns 418. Nginx should successfully start (in particular, the `default_server` in the # custom config should not conflict with the fallback server generated by nginx-proxy) and nginx @@ -100,5 +97,5 @@ def test_fallback(get, url, want_code, want_err_re): r = get(url) assert r.status_code == want_code else: - with pytest.raises(requests.exceptions.RequestException, match=want_err_re): + with pytest.raises(requests.exceptions.SSLError, match=want_err_re): get(url) diff --git a/test/test_htpasswd/htpasswd/561032515ede3ab3a015edfb244608b72409c430 b/test/test_htpasswd/htpasswd/561032515ede3ab3a015edfb244608b72409c430 new file mode 100644 index 000000000..336275a1b --- /dev/null +++ b/test/test_htpasswd/htpasswd/561032515ede3ab3a015edfb244608b72409c430 @@ -0,0 +1 @@ +vhost:$2a$13$/aPYmoK0mmgyAI4TpKdFY.6441Ugo39MdXjhpm.Pp6D15rbz9tvz. diff --git a/test/test_htpasswd/htpasswd/htpasswd.nginx-proxy.tld b/test/test_htpasswd/htpasswd/htpasswd.nginx-proxy.tld new file mode 100644 index 000000000..336275a1b --- /dev/null +++ b/test/test_htpasswd/htpasswd/htpasswd.nginx-proxy.tld @@ -0,0 +1 @@ +vhost:$2a$13$/aPYmoK0mmgyAI4TpKdFY.6441Ugo39MdXjhpm.Pp6D15rbz9tvz. diff --git a/test/test_htpasswd/htpasswd/htpasswd.nginx-proxy.tld_8d960560c82f4e6c8b1b0f03eb30a1afd00e5696 b/test/test_htpasswd/htpasswd/htpasswd.nginx-proxy.tld_8d960560c82f4e6c8b1b0f03eb30a1afd00e5696 new file mode 100644 index 000000000..9816a8372 --- /dev/null +++ b/test/test_htpasswd/htpasswd/htpasswd.nginx-proxy.tld_8d960560c82f4e6c8b1b0f03eb30a1afd00e5696 @@ -0,0 +1 @@ +vpath:$2a$13$/aPYmoK0mmgyAI4TpKdFY.6441Ugo39MdXjhpm.Pp6D15rbz9tvz. diff --git a/test/test_htpasswd/test_htpasswd_regex_virtual_host.py b/test/test_htpasswd/test_htpasswd_regex_virtual_host.py new file mode 100644 index 000000000..1b169d001 --- /dev/null +++ b/test/test_htpasswd/test_htpasswd_regex_virtual_host.py @@ -0,0 +1,13 @@ +import pytest + +def test_htpasswd_regex_virtual_host_is_restricted(docker_compose, nginxproxy): + r = nginxproxy.get("http://regex.htpasswd.nginx-proxy.example/port") + assert r.status_code == 401 + assert "WWW-Authenticate" in r.headers + assert r.headers["WWW-Authenticate"] == 'Basic realm="Restricted access"' + + +def test_htpasswd_regex_virtual_host_basic_auth(docker_compose, nginxproxy): + r = nginxproxy.get("http://regex.htpasswd.nginx-proxy.example/port", auth=("vhost", "password")) + assert r.status_code == 200 + assert r.text == "answer from port 80\n" diff --git a/test/test_htpasswd/test_htpasswd_regex_virtual_host.yml b/test/test_htpasswd/test_htpasswd_regex_virtual_host.yml new file mode 100644 index 000000000..7f0d1bc96 --- /dev/null +++ b/test/test_htpasswd/test_htpasswd_regex_virtual_host.yml @@ -0,0 +1,17 @@ +version: "2" + +services: + regex: + image: web + expose: + - "80" + environment: + WEB_PORTS: 80 + VIRTUAL_HOST: ~^regex.*\.nginx-proxy\.example$ + + sut: + container_name: sut + image: nginxproxy/nginx-proxy:test + volumes: + - /var/run/docker.sock:/tmp/docker.sock:ro + - ./htpasswd:/etc/nginx/htpasswd:ro diff --git a/test/test_htpasswd/test_htpasswd_virtual_host.py b/test/test_htpasswd/test_htpasswd_virtual_host.py new file mode 100644 index 000000000..aff3a62ad --- /dev/null +++ b/test/test_htpasswd/test_htpasswd_virtual_host.py @@ -0,0 +1,13 @@ +import pytest + +def test_htpasswd_virtual_host_is_restricted(docker_compose, nginxproxy): + r = nginxproxy.get("http://htpasswd.nginx-proxy.tld/port") + assert r.status_code == 401 + assert "WWW-Authenticate" in r.headers + assert r.headers["WWW-Authenticate"] == 'Basic realm="Restricted htpasswd.nginx-proxy.tld"' + + +def test_htpasswd_virtual_host_basic_auth(docker_compose, nginxproxy): + r = nginxproxy.get("http://htpasswd.nginx-proxy.tld/port", auth=("vhost", "password")) + assert r.status_code == 200 + assert r.text == "answer from port 80\n" diff --git a/test/test_htpasswd/test_htpasswd_virtual_host.yml b/test/test_htpasswd/test_htpasswd_virtual_host.yml new file mode 100644 index 000000000..b3f15df9e --- /dev/null +++ b/test/test_htpasswd/test_htpasswd_virtual_host.yml @@ -0,0 +1,17 @@ +version: "2" + +services: + web: + image: web + expose: + - "80" + environment: + WEB_PORTS: 80 + VIRTUAL_HOST: htpasswd.nginx-proxy.tld + + sut: + container_name: sut + image: nginxproxy/nginx-proxy:test + volumes: + - /var/run/docker.sock:/tmp/docker.sock:ro + - ./htpasswd:/etc/nginx/htpasswd:ro diff --git a/test/test_htpasswd/test_htpasswd_virtual_path.py b/test/test_htpasswd/test_htpasswd_virtual_path.py new file mode 100644 index 000000000..262b31472 --- /dev/null +++ b/test/test_htpasswd/test_htpasswd_virtual_path.py @@ -0,0 +1,12 @@ +import pytest + +def test_htpasswd_virtual_path_is_restricted(docker_compose, nginxproxy): + r = nginxproxy.get("http://htpasswd.nginx-proxy.tld/foo/port") + assert r.status_code == 401 + assert "WWW-Authenticate" in r.headers + assert r.headers["WWW-Authenticate"] == 'Basic realm="Restricted htpasswd.nginx-proxy.tld/foo/"' + +def test_htpasswd_virtual_path_basic_auth(docker_compose, nginxproxy): + r = nginxproxy.get("http://htpasswd.nginx-proxy.tld/foo/port", auth=("vpath", "password")) + assert r.status_code == 200 + assert r.text == "answer from port 80\n" diff --git a/test/test_htpasswd/test_htpasswd_virtual_path.yml b/test/test_htpasswd/test_htpasswd_virtual_path.yml new file mode 100644 index 000000000..ffe1a0858 --- /dev/null +++ b/test/test_htpasswd/test_htpasswd_virtual_path.yml @@ -0,0 +1,19 @@ +version: "2" + +services: + web: + image: web + expose: + - "80" + environment: + WEB_PORTS: 80 + VIRTUAL_HOST: htpasswd.nginx-proxy.tld + VIRTUAL_PATH: /foo/ + VIRTUAL_DEST: / + + sut: + container_name: sut + image: nginxproxy/nginx-proxy:test + volumes: + - /var/run/docker.sock:/tmp/docker.sock:ro + - ./htpasswd:/etc/nginx/htpasswd:ro diff --git a/test/test_http_port.py b/test/test_http_port.py index 26302c536..0bd6bb4af 100644 --- a/test/test_http_port.py +++ b/test/test_http_port.py @@ -5,4 +5,9 @@ def test_web1_http_custom_port(docker_compose, nginxproxy, subdomain): r = nginxproxy.get("http://%s.nginx-proxy.tld:8080/port" % subdomain, allow_redirects=False) assert r.status_code == 200 - assert "answer from port 81\n" in r.text \ No newline at end of file + assert "answer from port 81\n" in r.text + +def test_nonstandardport_Host_header(docker_compose, nginxproxy): + r = nginxproxy.get("http://web.nginx-proxy.tld:8080/headers") + assert r.status_code == 200 + assert "Host: web.nginx-proxy.tld:8080" in r.text diff --git a/test/test_logs/test_log_disabled.py b/test/test_logs/test_log_disabled.py new file mode 100644 index 000000000..2870b9057 --- /dev/null +++ b/test/test_logs/test_log_disabled.py @@ -0,0 +1,11 @@ +import pytest + +def test_log_disabled(docker_compose, nginxproxy): + r = nginxproxy.get("http://nginx-proxy.test/port") + assert r.status_code == 200 + assert r.text == "answer from port 81\n" + sut_container = docker_compose.containers.get("sut") + docker_logs = sut_container.logs(stdout=True, stderr=True, stream=False, follow=False) + docker_logs = docker_logs.decode("utf-8").splitlines() + docker_logs = [line for line in docker_logs if "GET /port" in line] + assert len(docker_logs) == 0 diff --git a/test/stress_tests/test_deleted_cert/docker-compose.yml b/test/test_logs/test_log_disabled.yml similarity index 60% rename from test/stress_tests/test_deleted_cert/docker-compose.yml rename to test/test_logs/test_log_disabled.yml index a362e443d..2d8a59c91 100644 --- a/test/stress_tests/test_deleted_cert/docker-compose.yml +++ b/test/test_logs/test_log_disabled.yml @@ -1,17 +1,18 @@ version: "2" services: - web: + web1: image: web expose: - "81" environment: WEB_PORTS: 81 - VIRTUAL_HOST: web.nginx-proxy + VIRTUAL_HOST: nginx-proxy.test - reverseproxy: + sut: + container_name: sut image: nginxproxy/nginx-proxy:test - container_name: reverseproxy volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - - ./tmp_certs:/etc/nginx/certs:ro + environment: + DISABLE_ACCESS_LOGS: true diff --git a/test/test_log_format.py b/test/test_logs/test_log_format.py similarity index 100% rename from test/test_log_format.py rename to test/test_logs/test_log_format.py diff --git a/test/test_log_format.yml b/test/test_logs/test_log_format.yml similarity index 100% rename from test/test_log_format.yml rename to test/test_logs/test_log_format.yml diff --git a/test/test_logs/test_log_json.py b/test/test_logs/test_log_json.py new file mode 100644 index 000000000..1a04b228c --- /dev/null +++ b/test/test_logs/test_log_json.py @@ -0,0 +1,14 @@ +import pytest + +def test_log_json(docker_compose, nginxproxy): + log_conf = [line for line in nginxproxy.get_conf().decode('ASCII').splitlines() if "log_format vhost escape=" in line] + assert "{\"time_local\":\"$time_iso8601\"," in log_conf[0] + + r = nginxproxy.get("http://nginx-proxy.test/port") + assert r.status_code == 200 + assert r.text == "answer from port 81\n" + sut_container = docker_compose.containers.get("sut") + docker_logs = sut_container.logs(stdout=True, stderr=True, stream=False, follow=False) + docker_logs = docker_logs.decode("utf-8").splitlines() + docker_logs = [line for line in docker_logs if "{\"time_local\":" in line] + assert "GET /port" in docker_logs[0] diff --git a/test/test_composev2.yml b/test/test_logs/test_log_json.yml similarity index 64% rename from test/test_composev2.yml rename to test/test_logs/test_log_json.yml index 3c36022b5..2e6fefdba 100644 --- a/test/test_composev2.yml +++ b/test/test_logs/test_log_json.yml @@ -1,15 +1,18 @@ version: "2" services: - nginx-proxy: - image: nginxproxy/nginx-proxy:test - volumes: - - /var/run/docker.sock:/tmp/docker.sock:ro - - web: + web1: image: web expose: - "81" environment: WEB_PORTS: 81 - VIRTUAL_HOST: web.nginx-proxy.example + VIRTUAL_HOST: nginx-proxy.test + + sut: + container_name: sut + image: nginxproxy/nginx-proxy:test + volumes: + - /var/run/docker.sock:/tmp/docker.sock:ro + environment: + LOG_JSON: 1 diff --git a/test/test_logs/test_log_json_format.py b/test/test_logs/test_log_json_format.py new file mode 100644 index 000000000..2d158cb7c --- /dev/null +++ b/test/test_logs/test_log_json_format.py @@ -0,0 +1,14 @@ +import pytest + +def test_log_json_format(docker_compose, nginxproxy): + log_conf = [line for line in nginxproxy.get_conf().decode('ASCII').splitlines() if "log_format vhost escape=" in line] + assert "{\"time_local\":\"$time_iso8601\"," in log_conf[0] + + r = nginxproxy.get("http://nginx-proxy.test/port") + assert r.status_code == 200 + assert r.text == "answer from port 81\n" + sut_container = docker_compose.containers.get("sut") + docker_logs = sut_container.logs(stdout=True, stderr=True, stream=False, follow=False) + docker_logs = docker_logs.decode("utf-8").splitlines() + docker_logs = [line for line in docker_logs if "{\"time_local\":" in line] + assert "GET /port" in docker_logs[0] diff --git a/test/test_logs/test_log_json_format.yml b/test/test_logs/test_log_json_format.yml new file mode 100644 index 000000000..5e01e924f --- /dev/null +++ b/test/test_logs/test_log_json_format.yml @@ -0,0 +1,18 @@ +version: "2" + +services: + web1: + image: web + expose: + - "81" + environment: + WEB_PORTS: 81 + VIRTUAL_HOST: nginx-proxy.test + + sut: + container_name: sut + image: nginxproxy/nginx-proxy:test + volumes: + - /var/run/docker.sock:/tmp/docker.sock:ro + environment: + LOG_FORMAT: '{"time_local":"$$time_iso8601","remote_addr":"$$remote_addr","request":"$$request","upstream_addr":"$$upstream_addr"}' diff --git a/test/test_multiports/test_multiports-base-json.py b/test/test_multiports/test_multiports-base-json.py new file mode 100644 index 000000000..7f1ef0fb0 --- /dev/null +++ b/test/test_multiports/test_multiports-base-json.py @@ -0,0 +1,39 @@ +import pytest + + +def test_virtual_host_is_dropped_when_using_multiports(docker_compose, nginxproxy): + r = nginxproxy.get("http://notskipped.nginx-proxy.tld/port") + assert r.status_code == 200 + assert "answer from port 81\n" in r.text + r = nginxproxy.get("http://skipped.nginx-proxy.tld/") + assert r.status_code == 503 + + +def test_answer_is_served_from_port_80_by_default(docker_compose, nginxproxy): + r = nginxproxy.get("http://port80.a.nginx-proxy.tld/port") + assert r.status_code == 200 + assert "answer from port 80\n" in r.text + r = nginxproxy.get("http://port80.b.nginx-proxy.tld/port") + assert r.status_code == 200 + assert "answer from port 80\n" in r.text + r = nginxproxy.get("http://port80.c.nginx-proxy.tld/port") + assert r.status_code == 200 + assert "answer from port 80\n" in r.text + + +def test_answer_is_served_from_chosen_ports(docker_compose, nginxproxy): + r = nginxproxy.get("http://port8080.nginx-proxy.tld/port") + assert r.status_code == 200 + assert "answer from port 8080\n" in r.text + r = nginxproxy.get("http://port9000.nginx-proxy.tld/port") + assert r.status_code == 200 + assert "answer from port 9000\n" in r.text + + +def test_answer_is_served_from_chosen_ports_and_dest(docker_compose, nginxproxy): + r = nginxproxy.get("http://virtualpaths.nginx-proxy.tld/rootdest/port") + assert r.status_code == 200 + assert "answer from port 10001\n" in r.text + r = nginxproxy.get("http://virtualpaths.nginx-proxy.tld/customdest") + assert r.status_code == 200 + assert "answer from port 10002\n" in r.text diff --git a/test/test_multiports/test_multiports-base-json.yml b/test/test_multiports/test_multiports-base-json.yml new file mode 100644 index 000000000..fc0d0fa81 --- /dev/null +++ b/test/test_multiports/test_multiports-base-json.yml @@ -0,0 +1,77 @@ +version: "2" + +services: + skipvirtualhost: + image: web + expose: + - "81" + environment: + WEB_PORTS: "81" + VIRTUAL_HOST: skipped.nginx-proxy.tld + VIRTUAL_HOST_MULTIPORTS: |- + { + "notskipped.nginx-proxy.tld": {} + } + + defaultport: + image: web + expose: + - "80" + - "8080" + environment: + WEB_PORTS: "80 8080" + VIRTUAL_HOST_MULTIPORTS: |- + { + "port80.a.nginx-proxy.tld": {}, + "port80.b.nginx-proxy.tld": {}, + "port80.c.nginx-proxy.tld": { + "/": {} + } + } + + multiports: + image: web + expose: + - "8080" + - "9000" + environment: + WEB_PORTS: "8080 9000" + VIRTUAL_HOST_MULTIPORTS: |- + { + "port8080.nginx-proxy.tld": { + "/": { + "port": 8080 + } + }, + "port9000.nginx-proxy.tld": { + "/": { + "port": 9000 + } + } + } + + virtualpath: + image: web + expose: + - "10001" + - "10002" + environment: + WEB_PORTS: "10001 10002" + VIRTUAL_HOST_MULTIPORTS: |- + { + "virtualpaths.nginx-proxy.tld": { + "/rootdest": { + "port": 10001, + "dest": "/" + }, + "/customdest": { + "port": 10002, + "dest": "/port" + } + } + } + + sut: + image: nginxproxy/nginx-proxy:test + volumes: + - /var/run/docker.sock:/tmp/docker.sock:ro diff --git a/test/test_multiports/test_multiports-base-yaml.py b/test/test_multiports/test_multiports-base-yaml.py new file mode 100644 index 000000000..7f1ef0fb0 --- /dev/null +++ b/test/test_multiports/test_multiports-base-yaml.py @@ -0,0 +1,39 @@ +import pytest + + +def test_virtual_host_is_dropped_when_using_multiports(docker_compose, nginxproxy): + r = nginxproxy.get("http://notskipped.nginx-proxy.tld/port") + assert r.status_code == 200 + assert "answer from port 81\n" in r.text + r = nginxproxy.get("http://skipped.nginx-proxy.tld/") + assert r.status_code == 503 + + +def test_answer_is_served_from_port_80_by_default(docker_compose, nginxproxy): + r = nginxproxy.get("http://port80.a.nginx-proxy.tld/port") + assert r.status_code == 200 + assert "answer from port 80\n" in r.text + r = nginxproxy.get("http://port80.b.nginx-proxy.tld/port") + assert r.status_code == 200 + assert "answer from port 80\n" in r.text + r = nginxproxy.get("http://port80.c.nginx-proxy.tld/port") + assert r.status_code == 200 + assert "answer from port 80\n" in r.text + + +def test_answer_is_served_from_chosen_ports(docker_compose, nginxproxy): + r = nginxproxy.get("http://port8080.nginx-proxy.tld/port") + assert r.status_code == 200 + assert "answer from port 8080\n" in r.text + r = nginxproxy.get("http://port9000.nginx-proxy.tld/port") + assert r.status_code == 200 + assert "answer from port 9000\n" in r.text + + +def test_answer_is_served_from_chosen_ports_and_dest(docker_compose, nginxproxy): + r = nginxproxy.get("http://virtualpaths.nginx-proxy.tld/rootdest/port") + assert r.status_code == 200 + assert "answer from port 10001\n" in r.text + r = nginxproxy.get("http://virtualpaths.nginx-proxy.tld/customdest") + assert r.status_code == 200 + assert "answer from port 10002\n" in r.text diff --git a/test/test_multiports/test_multiports-base-yaml.yml b/test/test_multiports/test_multiports-base-yaml.yml new file mode 100644 index 000000000..8bd58030c --- /dev/null +++ b/test/test_multiports/test_multiports-base-yaml.yml @@ -0,0 +1,61 @@ +version: "2" + +services: + skipvirtualhost: + image: web + expose: + - "81" + environment: + WEB_PORTS: "81" + VIRTUAL_HOST: skipped.nginx-proxy.tld + VIRTUAL_HOST_MULTIPORTS: |- + notskipped.nginx-proxy.tld: + + defaultport: + image: web + expose: + - "80" + - "8080" + environment: + WEB_PORTS: "80 8080" + VIRTUAL_HOST_MULTIPORTS: |- + port80.a.nginx-proxy.tld: + port80.b.nginx-proxy.tld: + port80.c.nginx-proxy.tld: + "/": + + multiports: + image: web + expose: + - "8080" + - "9000" + environment: + WEB_PORTS: "8080 9000" + VIRTUAL_HOST_MULTIPORTS: |- + port8080.nginx-proxy.tld: + "/": + port: 8080 + port9000.nginx-proxy.tld: + "/": + port: 9000 + + virtualpath: + image: web + expose: + - "10001" + - "10002" + environment: + WEB_PORTS: "10001 10002" + VIRTUAL_HOST_MULTIPORTS: |- + virtualpaths.nginx-proxy.tld: + "/rootdest": + port: 10001 + dest: "/" + "/customdest": + port: 10002 + dest: "/port" + + sut: + image: nginxproxy/nginx-proxy:test + volumes: + - /var/run/docker.sock:/tmp/docker.sock:ro diff --git a/test/test_multiports/test_multiports-invalid-syntax.py b/test/test_multiports/test_multiports-invalid-syntax.py new file mode 100644 index 000000000..ed1c77338 --- /dev/null +++ b/test/test_multiports/test_multiports-invalid-syntax.py @@ -0,0 +1,18 @@ +import pytest +import re + + +def test_virtual_hosts_with_syntax_error_should_not_be_reachable(docker_compose, nginxproxy): + r = nginxproxy.get("http://test1.nginx-proxy.tld") + assert r.status_code == 503 + r = nginxproxy.get("http://test2.nginx-proxy.tld") + assert r.status_code == 503 + + +def test_config_should_have_multiports_warning_comments(docker_compose, nginxproxy): + conf = nginxproxy.get_conf().decode('ASCII') + matches = re.findall(r"the VIRTUAL_HOST_MULTIPORTS environment variable used for this container is not a valid YAML string", conf) + assert len(matches) == 3 + assert "# invalidsyntax" in conf + assert "# hostnamerepeat" in conf + assert "# pathrepeat" in conf diff --git a/test/test_multiports/test_multiports-invalid-syntax.yml b/test/test_multiports/test_multiports-invalid-syntax.yml new file mode 100644 index 000000000..9f4022061 --- /dev/null +++ b/test/test_multiports/test_multiports-invalid-syntax.yml @@ -0,0 +1,44 @@ +version: "2" + +services: + invalidsyntax: + image: web + container_name: invalidsyntax + expose: + - "80" + environment: + WEB_PORTS: "80" + VIRTUAL_HOST_MULTIPORTS: |- + test1.nginx-proxy.tld + test2.nginx-proxy.tld: + + hostnamerepeat: + image: web + container_name: hostnamerepeat + expose: + - "80" + environment: + WEB_PORTS: "80" + VIRTUAL_HOST_MULTIPORTS: |- + test1.nginx-proxy.tld: + test1.nginx-proxy.tld: + + pathrepeat: + image: web + container_name: pathrepeat + expose: + - "8080" + - "9000" + environment: + WEB_PORTS: "8080 9000" + VIRTUAL_HOST_MULTIPORTS: |- + test1.nginx-proxy.tld: + "/": + port: 8080 + "/": + port: 9000 + + sut: + image: nginxproxy/nginx-proxy:test + volumes: + - /var/run/docker.sock:/tmp/docker.sock:ro diff --git a/test/test_multiports/test_multiports-merge.py b/test/test_multiports/test_multiports-merge.py new file mode 100644 index 000000000..f5aa69782 --- /dev/null +++ b/test/test_multiports/test_multiports-merge.py @@ -0,0 +1,14 @@ +import backoff +import pytest + + +def test_multiports_and_legacy_configs_should_be_merged(docker_compose, nginxproxy): + @backoff.on_predicate(backoff.constant, lambda r: r == False, interval=.5, max_tries=20, jitter=None) + def answer_contains(answer, url): + return answer in nginxproxy.get(url).text + + assert answer_contains("80", "http://merged.nginx-proxy.tld/port") + assert answer_contains("81", "http://merged.nginx-proxy.tld/port") + + assert answer_contains("9090", "http://merged.nginx-proxy.tld/foo/port") + assert answer_contains("9191", "http://merged.nginx-proxy.tld/foo/port") diff --git a/test/test_multiports/test_multiports-merge.yml b/test/test_multiports/test_multiports-merge.yml new file mode 100644 index 000000000..5c5cd8bd0 --- /dev/null +++ b/test/test_multiports/test_multiports-merge.yml @@ -0,0 +1,41 @@ +version: "2" + +services: + merged-singleport: + image: web + expose: + - "80" + environment: + WEB_PORTS: "80" + VIRTUAL_HOST: merged.nginx-proxy.tld + + merged-singleport-virtual-path: + image: web + expose: + - "9090" + environment: + WEB_PORTS: "9090" + VIRTUAL_HOST: merged.nginx-proxy.tld + VIRTUAL_PORT: "9090" + VIRTUAL_PATH: "/foo" + VIRTUAL_DEST: "/" + + merged-multiports: + image: web + expose: + - "81" + - "9191" + environment: + WEB_PORTS: "81 9191" + VIRTUAL_HOST_MULTIPORTS: |- + merged.nginx-proxy.tld: + "/": + port: 81 + "/foo": + port: 9191 + dest: "/" + + sut: + image: nginxproxy/nginx-proxy:test + volumes: + - /var/run/docker.sock:/tmp/docker.sock:ro diff --git a/test/test_multiple-ports/test_VIRTUAL_PORT-single-different-from-single-port.py b/test/test_ports/test_VIRTUAL_PORT-single-different-from-single-port.py similarity index 100% rename from test/test_multiple-ports/test_VIRTUAL_PORT-single-different-from-single-port.py rename to test/test_ports/test_VIRTUAL_PORT-single-different-from-single-port.py diff --git a/test/test_multiple-ports/test_VIRTUAL_PORT-single-different-from-single-port.yml b/test/test_ports/test_VIRTUAL_PORT-single-different-from-single-port.yml similarity index 100% rename from test/test_multiple-ports/test_VIRTUAL_PORT-single-different-from-single-port.yml rename to test/test_ports/test_VIRTUAL_PORT-single-different-from-single-port.yml diff --git a/test/test_multiple-ports/test_VIRTUAL_PORT.py b/test/test_ports/test_VIRTUAL_PORT.py similarity index 100% rename from test/test_multiple-ports/test_VIRTUAL_PORT.py rename to test/test_ports/test_VIRTUAL_PORT.py diff --git a/test/test_multiple-ports/test_VIRTUAL_PORT.yml b/test/test_ports/test_VIRTUAL_PORT.yml similarity index 100% rename from test/test_multiple-ports/test_VIRTUAL_PORT.yml rename to test/test_ports/test_VIRTUAL_PORT.yml diff --git a/test/test_multiple-ports/test_default-80.py b/test/test_ports/test_default-80.py similarity index 100% rename from test/test_multiple-ports/test_default-80.py rename to test/test_ports/test_default-80.py diff --git a/test/test_multiple-ports/test_default-80.yml b/test/test_ports/test_default-80.yml similarity index 100% rename from test/test_multiple-ports/test_default-80.yml rename to test/test_ports/test_default-80.yml diff --git a/test/test_multiple-ports/test_single-port-not-80.py b/test/test_ports/test_single-port-not-80.py similarity index 100% rename from test/test_multiple-ports/test_single-port-not-80.py rename to test/test_ports/test_single-port-not-80.py diff --git a/test/test_multiple-ports/test_single-port-not-80.yml b/test/test_ports/test_single-port-not-80.yml similarity index 100% rename from test/test_multiple-ports/test_single-port-not-80.yml rename to test/test_ports/test_single-port-not-80.yml diff --git a/test/test_ssl/acme_root/.well-known/acme-challenge/test-filename b/test/test_ssl/acme_root/.well-known/acme-challenge/test-filename new file mode 100644 index 000000000..5b45dff28 --- /dev/null +++ b/test/test_ssl/acme_root/.well-known/acme-challenge/test-filename @@ -0,0 +1 @@ +challenge-teststring diff --git a/test/test_ssl/test_https_port.py b/test/test_ssl/test_https_port.py index 214d4d938..ebe305f70 100644 --- a/test/test_ssl/test_https_port.py +++ b/test/test_ssl/test_https_port.py @@ -11,4 +11,18 @@ def test_web1_http_redirects_to_https(docker_compose, nginxproxy, subdomain): def test_web1_https_is_forwarded(docker_compose, nginxproxy, subdomain): r = nginxproxy.get("https://%s.nginx-proxy.tld:8443/port" % subdomain, allow_redirects=False) assert r.status_code == 200 - assert "answer from port 81\n" in r.text \ No newline at end of file + assert "answer from port 81\n" in r.text + +def test_nonstandardport_Host_header(docker_compose, nginxproxy): + r = nginxproxy.get("https://web.nginx-proxy.tld:8443/headers") + assert r.status_code == 200 + assert "Host: web.nginx-proxy.tld:8443" in r.text + +@pytest.mark.parametrize("subdomain", ["foo", "bar"]) +def test_web1_acme_challenge_works(docker_compose, nginxproxy, acme_challenge_path, subdomain): + r = nginxproxy.get( + f"http://{subdomain}.nginx-proxy.tld:8080/{acme_challenge_path}", + allow_redirects=False + ) + assert r.status_code == 200 + assert "challenge-teststring\n" in r.text diff --git a/test/test_ssl/test_https_port.yml b/test/test_ssl/test_https_port.yml index 047054a39..b6541acb0 100644 --- a/test/test_ssl/test_https_port.yml +++ b/test/test_ssl/test_https_port.yml @@ -14,6 +14,7 @@ services: volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - ./certs:/etc/nginx/certs:ro + - ./acme_root:/usr/share/nginx/html:ro environment: HTTP_PORT: 8080 HTTPS_PORT: 8443 diff --git a/test/test_ssl/test_nohttp.py b/test/test_ssl/test_nohttp.py index 5b650db4f..032f60fd4 100644 --- a/test/test_ssl/test_nohttp.py +++ b/test/test_ssl/test_nohttp.py @@ -3,8 +3,15 @@ def test_web2_http_is_connection_refused(docker_compose, nginxproxy): - with pytest.raises(requests.exceptions.RequestException, match="Connection refused"): - nginxproxy.get("http://web2.nginx-proxy.tld/") + r = nginxproxy.get("http://web2.nginx-proxy.tld/", allow_redirects=False) + assert r.status_code == 503 + + +def test_web2_http_is_connection_refused_for_acme_challenge( + docker_compose, nginxproxy, acme_challenge_path +): + r = nginxproxy.get(f"http://web2.nginx-proxy.tld/{acme_challenge_path}", allow_redirects=False) + assert r.status_code == 503 def test_web2_https_is_forwarded(docker_compose, nginxproxy): diff --git a/test/test_ssl/test_nohttp.yml b/test/test_ssl/test_nohttp.yml index 40b393ad6..0c21bf9ca 100644 --- a/test/test_ssl/test_nohttp.yml +++ b/test/test_ssl/test_nohttp.yml @@ -15,3 +15,4 @@ services: volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - ./certs:/etc/nginx/certs:ro + - ./acme_root:/usr/share/nginx/html:ro diff --git a/test/test_ssl/test_nohttps.py b/test/test_ssl/test_nohttps.py index 1cedf8218..23e822477 100644 --- a/test/test_ssl/test_nohttps.py +++ b/test/test_ssl/test_nohttps.py @@ -10,3 +10,11 @@ def test_http_is_forwarded(docker_compose, nginxproxy): def test_https_is_disabled(docker_compose, nginxproxy): with pytest.raises(ConnectionError): nginxproxy.get("https://web.nginx-proxy.tld/", allow_redirects=False) + + +def test_http_acme_challenge_does_not_work(docker_compose, nginxproxy, acme_challenge_path): + r = nginxproxy.get( + f"http://web.nginx-proxy.tld/{acme_challenge_path}", + allow_redirects=False + ) + assert r.status_code == 404 diff --git a/test/test_ssl/test_nohttps.yml b/test/test_ssl/test_nohttps.yml index f2b07574b..209f57a8c 100644 --- a/test/test_ssl/test_nohttps.yml +++ b/test/test_ssl/test_nohttps.yml @@ -14,3 +14,4 @@ services: image: nginxproxy/nginx-proxy:test volumes: - /var/run/docker.sock:/tmp/docker.sock:ro + - ./acme_root:/usr/share/nginx/html:ro diff --git a/test/test_ssl/test_noredirect.py b/test/test_ssl/test_noredirect.py index 62df28b13..1d956d198 100644 --- a/test/test_ssl/test_noredirect.py +++ b/test/test_ssl/test_noredirect.py @@ -16,4 +16,12 @@ def test_web3_https_is_forwarded(docker_compose, nginxproxy): def test_web2_HSTS_policy_is_inactive(docker_compose, nginxproxy): r = nginxproxy.get("https://web3.nginx-proxy.tld/port", allow_redirects=False) assert "answer from port 83\n" in r.text - assert "Strict-Transport-Security" not in r.headers \ No newline at end of file + assert "Strict-Transport-Security" not in r.headers + + +def test_web3_acme_challenge_does_work(docker_compose, nginxproxy, acme_challenge_path): + r = nginxproxy.get( + f"http://web3.nginx-proxy.tld/{acme_challenge_path}", + allow_redirects=False + ) + assert r.status_code == 200 diff --git a/test/test_ssl/test_noredirect.yml b/test/test_ssl/test_noredirect.yml index 8ee845525..7610ae212 100644 --- a/test/test_ssl/test_noredirect.yml +++ b/test/test_ssl/test_noredirect.yml @@ -15,3 +15,4 @@ services: volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - ./certs:/etc/nginx/certs:ro + - ./acme_root:/usr/share/nginx/html:ro diff --git a/test/test_ssl/test_virtual_path.py b/test/test_ssl/test_virtual_path.py index 508653f24..72ac433b9 100644 --- a/test/test_ssl/test_virtual_path.py +++ b/test/test_ssl/test_virtual_path.py @@ -1,4 +1,5 @@ import pytest +from requests import ConnectionError @pytest.mark.parametrize("path", ["web1", "web2"]) def test_web1_http_redirects_to_https(docker_compose, nginxproxy, path): @@ -13,3 +14,11 @@ def test_web1_https_is_forwarded(docker_compose, nginxproxy, path, port): assert r.status_code == 200 assert "answer from port %d\n" % port in r.text + +@pytest.mark.parametrize("port", [81, 82]) +def test_acme_challenge_does_not_work(docker_compose, nginxproxy, acme_challenge_path, port): + with pytest.raises(ConnectionError): + nginxproxy.get( + f"http://www.nginx-proxy.tld:{port}/{acme_challenge_path}", + allow_redirects=False + ) diff --git a/test/test_ssl/test_virtual_path.yml b/test/test_ssl/test_virtual_path.yml index 2494d35d8..eb09ef0f6 100644 --- a/test/test_ssl/test_virtual_path.yml +++ b/test/test_ssl/test_virtual_path.yml @@ -26,3 +26,4 @@ services: volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - ./certs:/etc/nginx/certs:ro + - ./acme_root:/usr/share/nginx/html:ro diff --git a/test/test_ssl/test_wildcard.py b/test/test_ssl/test_wildcard.py index 202ba247e..f019f68ef 100644 --- a/test/test_ssl/test_wildcard.py +++ b/test/test_ssl/test_wildcard.py @@ -21,3 +21,13 @@ def test_web1_HSTS_policy_is_active(docker_compose, nginxproxy, subdomain): r = nginxproxy.get(f"https://{subdomain}.nginx-proxy.tld/port", allow_redirects=False) assert "answer from port 81\n" in r.text assert "Strict-Transport-Security" in r.headers + + +@pytest.mark.parametrize("subdomain", ["foo", "bar"]) +def test_web1_acme_challenge_works(docker_compose, nginxproxy, acme_challenge_path, subdomain): + r = nginxproxy.get( + f"http://web3.nginx-proxy.tld/{acme_challenge_path}", + allow_redirects=False + ) + assert r.status_code == 200 + assert "challenge-teststring\n" in r.text diff --git a/test/test_ssl/test_wildcard.yml b/test/test_ssl/test_wildcard.yml index ea8c596cc..b101e9f11 100644 --- a/test/test_ssl/test_wildcard.yml +++ b/test/test_ssl/test_wildcard.yml @@ -14,3 +14,4 @@ services: volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - ./certs:/etc/nginx/certs:ro + - ./acme_root:/usr/share/nginx/html:ro diff --git a/test/test_ssl/wildcard_cert_and_nohttps/acme_root/.well-known/acme-challenge/test-filename b/test/test_ssl/wildcard_cert_and_nohttps/acme_root/.well-known/acme-challenge/test-filename new file mode 100644 index 000000000..5b45dff28 --- /dev/null +++ b/test/test_ssl/wildcard_cert_and_nohttps/acme_root/.well-known/acme-challenge/test-filename @@ -0,0 +1 @@ +challenge-teststring diff --git a/test/test_ssl/wildcard_cert_and_nohttps/docker-compose.yml b/test/test_ssl/wildcard_cert_and_nohttps/docker-compose.yml index 98f41a0a2..7cc64e76d 100644 --- a/test/test_ssl/wildcard_cert_and_nohttps/docker-compose.yml +++ b/test/test_ssl/wildcard_cert_and_nohttps/docker-compose.yml @@ -7,6 +7,7 @@ services: volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - ./certs:/etc/nginx/certs:ro + - ./acme_root:/usr/share/nginx/html:ro web1: image: web diff --git a/test/test_ssl/wildcard_cert_and_nohttps/test_wildcard_cert_nohttps.py b/test/test_ssl/wildcard_cert_and_nohttps/test_wildcard_cert_nohttps.py index 445377912..d07437d76 100644 --- a/test/test_ssl/wildcard_cert_and_nohttps/test_wildcard_cert_nohttps.py +++ b/test/test_ssl/wildcard_cert_and_nohttps/test_wildcard_cert_nohttps.py @@ -1,5 +1,6 @@ import pytest from ssl import CertificateError +from requests import ConnectionError from requests.exceptions import SSLError @@ -32,3 +33,25 @@ def test_https_request_to_nohttps_vhost_goes_to_fallback_server(docker_compose, r = nginxproxy.get("https://3.web.nginx-proxy.tld/port", verify=False) assert r.status_code == 503 + + +@pytest.mark.parametrize("subdomain,acme_should_work", [ + (1, True), + (2, True), + (3, False), +]) +def test_acme_challenge_works( + docker_compose, nginxproxy, acme_challenge_path, subdomain, acme_should_work +): + if acme_should_work: + r = nginxproxy.get( + f"https://{subdomain}.web.nginx-proxy.tld/{acme_challenge_path}", + allow_redirects=False + ) + assert r.status_code == 404 + else: + with pytest.raises(ConnectionError): + nginxproxy.get( + f"https://{subdomain}.web.nginx-proxy.tld/{acme_challenge_path}", + allow_redirects=False + ) diff --git a/test/test_default-root-none.py b/test/test_virtual-path/test_default-root-none.py similarity index 100% rename from test/test_default-root-none.py rename to test/test_virtual-path/test_default-root-none.py diff --git a/test/test_default-root-none.yml b/test/test_virtual-path/test_default-root-none.yml similarity index 100% rename from test/test_default-root-none.yml rename to test/test_virtual-path/test_default-root-none.yml