Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

influxDB2.0 alpha - http custom base path #15721

Open
steverweber opened this issue Nov 1, 2019 · 75 comments
Open

influxDB2.0 alpha - http custom base path #15721

steverweber opened this issue Nov 1, 2019 · 75 comments
Labels
area/ui area/2.x OSS 2.0 related issues and PRs wontfix

Comments

@steverweber
Copy link

steverweber commented Nov 1, 2019

Trying to serve influxdb v2.0alpha through nginx proxy because I need to run multiple websites on the same host while admins only allow one port to be open 443.

https://dnsname/influxdb2

influxdb http page is referencing the root url path to load the site .js also noticed <base href="/"> is the url root.

is their some header that I should be passing upstream to influxdb so it knows to use a different basepath? or could an option be added to influxd so the base path can be custom?

Thanks!

<!doctype html>
<html>
<head><meta http-equiv="Content-type" content="text/html;charset=utf-8width=device-width,initial-scale=1" name="viewport"><title>InfluxDB 2.0</title><base href="/">
<link rel="shortcut icon" href="/favicon.ico"></head>
<body><div id="react-root" data-basepath=""></div>
<!-- want this to be something like: influxdb2/a02e0ac4f4.js  or a02e0ac4f4.js and use base href="/influxdb2/" -->
<script src="/a02e0ac4f4.js"></script>
</body></html>
@steverweber
Copy link
Author

looking at the code git checkout v2.0.0-alpha.19 i see some env vars... but setting them didn't help.

systemd...

Environment="STATIC_PREFIX=/influxdb2/"
Environment="API_PREFIX=/influxdb2/"
Environment="BASE_PATH=/influxdb2/"
Environment="API_BASE_PATH=/influxdb2/"
ExecStart=/srv/influxd

also seems that the option is in Chronograf looking at the readme

./chronograf/README.md:Change the default root path of the Chronograf server with the `--basepath`

perhaps this should be made available on influxd --basepath=/influxdb2/

@stale
Copy link

stale bot commented Jan 30, 2020

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@stale stale bot added the wontfix label Jan 30, 2020
@steverweber
Copy link
Author

please provide some feedback before closing.
Thanks.

@stale stale bot removed the wontfix label Jan 30, 2020
@drdelambre
Copy link
Contributor

For the base path parameters.. those are for configuring the frontend during compilation to allow it to be run behind a proxy, so they're already baked in by the time the image is pushed to the registry. Here's an example dockerfile that I use when i want to expose the frontend on a different url, passing those environment variables as build ARGs:

FROM ubuntu:bionic AS base

RUN apt-get update -y && \
    apt-get install -y \
        nginx \
        build-essential \
        curl \
        git

FROM base AS repo
WORKDIR /repo

ARG STATIC_DIRECTORY
ARG BASE_PATH
ARG API_BASE_PATH

ENV PATH="/node/bin:${PATH}"
RUN mkdir /node && \
    curl -sL https://git.io/n-install | N_PREFIX=/node bash -s -- -q && \
    npm i -g yarn

RUN git clone git://github.com/influxdata/influxdb.git && \
    cd ./influxdb

WORKDIR /repo/influxdb/ui

# these are all run together as docker's caching mechanism
# makes big steps like yarn install expensive
RUN yarn install --production=false && \
    yarn generate && \
    INFLUXDB_SHA=remote $(npm bin)/webpack --config ./webpack.prod.ts --bail && \
    rm -rf ./node_modules

FROM base AS deploy
WORKDIR /repo
COPY --from=repo /repo/influxdb/ui/build /usr/share/nginx/html
COPY ./nginx.conf /etc/nginx/nginx.conf
RUN useradd --no-create-home nginx

CMD ["nginx", "-g", "daemon off;"]

with just a simple nginx config in ./nginx.conf that hosts the files in `/usr/share/nginx/html' as your desired path:

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

    server_name _;

    # Path for static files
    root /usr/share/nginx/html;

    location / {
      try_files $uri /index.html;
    }
  }

@kwinkel
Copy link

kwinkel commented Aug 26, 2020

Rebuilding the UI with a variable seems not to be a solution. Setting an environment variable to override the base href and/or taking this from the request X-Forwarded-Prefix would be necessary to run influxdb2 behind a proxy with a subdirectory.

@CLKBlu3
Copy link

CLKBlu3 commented Sep 23, 2020

Having a similar issue.
I did follow https://gist.github.com/mvadu/5fbb7f5676ce31f2b1e6 from an older version to try setting up things.
However, it only loads the login page at http://mydomain.com/influxdb/, which doesn't work.

My setup is:
(relevant parts only)
nginx.conf:

upstream influxdb {
		server localhost:8086;
		keepalive 10;
	}
	#check the referer to identify requests originated by Influx UI
	map $http_referer $proxyloc {	
		~*influx influxdb;
	}
	
	#Influx Web API end points
	map $request_uri $backend {	
		~*query influxdb;
		~*write influxdb;
		~*ping  influxdb;
	}

server conf:

[...]
location / {
		if ($backend) {
			return 302 /$backend/$request_uri;
		}
	
		if ($proxyloc) {
			return 302 /$proxyloc/$uri;
		}
		# First attempt to serve request as file, then
		# as directory, then fall back to displaying a 404.
		try_files $uri $uri/ =404;
	}

	
	location /influxdb/ {
			
		proxy_pass	   http://localhost:8086/;
		proxy_set_header   Host			$http_host;
		proxy_set_header   X-Real-IP		$remote_addr;
		proxy_set_header   X-Forwarded-For	$proxy_add_x_forwarded_for;
	}
[...]

As said, my current configuration seems to load the login page fine, but it's unfunctional as it doesn't allow me access it.

Note: I use the docker container for influxdb2.0 beta from https://quay.io/repository/influxdb/influxdb?tag=2.0.0-beta&tab=tags

@cappelaere
Copy link

Similar issue! Grrrrrr!

@danxmoran danxmoran added area/2.x OSS 2.0 related issues and PRs area/ui labels Dec 14, 2020
@lephisto
Copy link

Is there any progress on this? I would really like to put Influx 2 OSS behind a reversproxy.

@nikosamus
Copy link

Same happening here, can't reverse proxy Influx 2.0. Even after many hours trying with apache html proxy for rewriting urls I can't get it working.

@CLKBlu3
Copy link

CLKBlu3 commented Jan 13, 2021

For people that had the same issue I did (commented a few months ago).
We managed to make it work by using subdomains. So if you have a domain (we got our certs with Certbot), I can recommend trying this.
We registered ours as mysubdomain.mydomain.com (sample name, obviously)
This way, all the paths should work, since we do not have a "custom" base path as we used to, but instead have a new "root" path that can match influxdb's ones without messing our configuration.

Sample nginx configuration:

server {
        server_name     mysubdomain.mydomain.com;

        location / {

                #access_log /var/log/nginx/influx-access.log influx buffer=1024 flush=5m;
                proxy_pass         http://localhost:xxxx/;
                proxy_set_header   Host                 $http_host;
                proxy_set_header   X-Real-IP            $remote_addr;
                proxy_set_header   X-Forwarded-For      $proxy_add_x_forwarded_for;
        }



    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/mysubdomain.mydomain.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/mysubdomain.mydomain.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
[...] # Other conf stuff

@steverweber
Copy link
Author

steverweber commented Jan 16, 2021

seems the only solution to date is recompiling the source code because the path is baked in.
workarounds:

Guess i'll just continue to ignore the influx UI and use the CLI for the odd admin task. Grafana runing under a custom base url is working out well for viewing data and setting alerts.

@YassineElbouchaibi
Copy link

Having the same issue... I just spent about 4 hours on it before finding this thread... For now I think I'll have to go with subdomain as no matter how I mess with the nginx config even if I get some web pages to load, some network requests just won't...

@monsdar
Copy link

monsdar commented Mar 10, 2021

Chiming in to put a bit more weight onto this issue. I've also just stumbled across this issue when trying to find a solution for the past hours. I wonder why this isn't troublesome for more people, using a reverse proxy with a custom subpath seems to be kind of a standard.

@ondrej-ivanko
Copy link

ondrej-ivanko commented Mar 15, 2021

Spend few days on this issue. So far it seems unresolvable without using subdomain for host based filtering in Ingress.

I needed to use InfluxDB UI behing nginx reverse proxy. With only one ingress-controller for the whole cluster. Turns out path based routing is possible with rewrite-target annotation in Ingress resource. But the Influx UI does not display at all. What ultimately cancelled any effort to use Ingress was that <base href="/"> thing, which doused any effort for us to use Ingress.

We would welcome any customization of base_href path, possibly via helm chart as we're using that for deployment.

One option could be to separate INFLUXD_HTTP_BIND_ADDRESS responsibility to server as address to InfluxDB API. And some other ENV_VAR would be responsible for settings path for Influx UI. It would have to be customizable via helm chart as well.

@gvasanka
Copy link

Having the same issue, spent almost a day finding a solution with trying out different configs. finally, I am here :)

Turns out path based routing is possible with rewrite-target annotation in Ingress resource. But the Influx UI does not display at all.

@ondrej-ivanko I hope what you mean is, you could access the influx DB API endpoints(write and query) using the path-based routing approach. but no luck in accessing UI.

If that's true can you share the working config with rewrite-target annotation?

@ondrej-ivanko
Copy link

@gvasanka I can't confirm that accessing API endpoints with rewrite-target annotation will work, as I haven't tried it. I don't see any reason, why it shouldn't work though.

If that's true can you share the working config with rewrite-target annotation?

Our company decided to abandon the effort to use Ingress controller. We just use port-forwarding of Influx pod for accessing UI.

@gvasanka
Copy link

@ondrej-ivanko Thank you very much for your answer.

I was able to get access to influxDb 2 API with the below Ingress config. Posting it here for other's usage in case somebody struggling.

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /$2
  name: influx-ingress-test
spec:
  rules:
  -  http:
      paths:
      - backend:
          serviceName: influxdb-release
          servicePort: 8086
        path: /influx(/|$)(.*)

But still no luck in getting access to the web.

@ecospecifier
Copy link

How is this not receiving more attention? Please can we get acknowledgement of the issue and get ENV access to set the base path like grafana has or appending to request url like even simple containers like adminer has. Apologies if I sound crass but having this hardcoded in is ridiculous. Running behind a reverse proxy nginx is something many people do and having to setup a subdomain just to workaround a HARDCODED base url is really silly.

Please try and give us some real commitment on this guys!

@RavilN
Copy link

RavilN commented Jun 21, 2021

I have a similar issue!

@jjriggs
Copy link

jjriggs commented Jun 26, 2021

Would like to also add my complaint to this thread. Grafana has a root_url parameter you can set in the config file. As far as I can tell, that is not the case with InfluxDB. Very frustrating that there appears to be no way for it to reside behind a reverse proxy without a subdomain.

@ingaa85
Copy link

ingaa85 commented Jun 29, 2021

I would also need this feature, as i dont want to use a second subdomain for this.

@depermana12
Copy link

+1

2 similar comments
@allej
Copy link

allej commented Feb 7, 2023

+1

@matheusbrunetti
Copy link

+1

@arun-prakash-fokus
Copy link

arun-prakash-fokus commented Mar 17, 2023

This is solution based on traefik with the plugin-rewritebody middleware

version: "3.9"
name: traefik-influxdb
services:
  influxdb:
    image: influxdb:2.6.1
    expose:
    - 8086
    labels:
      traefik.enable: "true"
      traefik.http.middlewares.influxdb_strip.stripprefix.prefixes: /influxdb
      traefik.http.middlewares.rewrite-foo.plugin.rewrite.lastModified: "true"
      traefik.http.middlewares.rewrite-foo.plugin.rewrite.rewrites[0].regex: src="/
      traefik.http.middlewares.rewrite-foo.plugin.rewrite.rewrites[0].replacement: src="/influxdb/
      traefik.http.middlewares.rewrite-foo.plugin.rewrite.rewrites[1].regex: href="/
      traefik.http.middlewares.rewrite-foo.plugin.rewrite.rewrites[1].replacement: href="/influxdb/
      traefik.http.middlewares.rewrite-foo.plugin.rewrite.rewrites[2].regex: data-basepath="
      traefik.http.middlewares.rewrite-foo.plugin.rewrite.rewrites[2].replacement: data-basepath="/influxdb/
      traefik.http.middlewares.rewrite-foo.plugin.rewrite.rewrites[3].regex: n.p="/"
      traefik.http.middlewares.rewrite-foo.plugin.rewrite.rewrites[3].replacement: n.p="/influxdb/"
      traefik.http.middlewares.rewrite-foo.plugin.rewrite.rewrites[4].regex: \)}/health`
      traefik.http.middlewares.rewrite-foo.plugin.rewrite.rewrites[4].replacement: )}/influxdb/health`
      traefik.http.routers.influxdb.entrypoints: websecure
      traefik.http.routers.influxdb.middlewares: rewrite-foo, influxdb_strip
      traefik.http.routers.influxdb.rule: PathPrefix(`/influxdb`) || PathPrefix(`/api`)
      traefik.http.routers.influxdb.tls: "true"
      traefik.http.services.influxdb.loadbalancer.server.port: "8086"
    networks:
      - default
    volumes:
      - influxdb.config:/etc/influxdb2
      - influxdb.data:/var/lib/influxdb2
  traefik:
    image: traefik:v2.9.6
    ports:
    - 5443:443
    environment:
      TRAEFIK_API_INSECURE: "false"
      TRAEFIK_ENTRYPOINTS_WEBSECURE_ADDRESS: :443
      TRAEFIK_EXPERIMENTAL_LOCALPLUGINS_REWRITE_MODULENAME: github.com/traefik/plugin-rewritebody
      TRAEFIK_LOG_LEVEL: DEBUG
      TRAEFIK_PING: "true"
      TRAEFIK_PROVIDERS_DOCKER: "true"
      TRAEFIK_PROVIDERS_DOCKER_EXPOSEDBYDEFAULT: "false"
    healthcheck:
      test:
      - CMD-SHELL
      - traefik healthcheck --ping
      timeout: 5s
      interval: 10s
      retries: 5
      start_period: 5s
    labels:
      traefik.enable: "true"
      traefik.http.middlewares.traefik-auth.basicauth.users: admin:$$apr1$$8EVjn/nj$$GiLUZqcbueTFeD23SuB6x0
      traefik.http.middlewares.traefik-strip.stripprefix.prefixes: /traefik
      traefik.http.routers.traefik_https.entrypoints: websecure
      traefik.http.routers.traefik_https.middlewares: traefik-auth,traefik-strip
      traefik.http.routers.traefik_https.rule: Host(`example.localhost`) && (PathPrefix(`/traefik`) || HeadersRegexp(`Referer`, `.*/traefik/.*`))
      traefik.http.routers.traefik_https.service: api@internal
      traefik.http.routers.traefik_https.tls: "true"
      traefik.http.services.traefik.loadbalancer.server.port: "443"
    networks:
      - default
    volumes:
      # - /var/run/docker.sock:/var/run/docker.sock # default docker context
      - /run/user/1000/docker.sock:/var/run/docker.sock # rootless docker context
      - ./traefik/plugins-local:/plugins-local
volumes:
  influxdb.config:
    name: influxdb-1-config
  influxdb.data:
    name: influxdb-1-data

image

image

In the browser, influxdb can be reached over

https://example.localhost:5443/influxdb

Screenshot from 2023-03-17 10-27-03

The influxdb api can be reached over

https://example.localhost:5443/influxdb/api/v2 or https://example.localhost:5443/api/v2

curl --insecure --location --request GET 'https://example.localhost:5443/influxdb/api/v2' \
--header 'Authorization: Token rEOYqouq5Vl4atAb4bGDox3vqNX_X0Tn2yHJV7jRqPlRz1lK0XxAiOLZADyulrdTCJ8nkmBNF_VjkmDAwLkODg==' \
--data-raw ''
{
    "authorizations": "/api/v2/authorizations",
    "backup": "/api/v2/backup",
    "buckets": "/api/v2/buckets",
    "checks": "/api/v2/checks",
    "dashboards": "/api/v2/dashboards",
    "delete": "/api/v2/delete",
    "external": {
        "statusFeed": "https://www.influxdata.com/feed/json"
    },
    "flags": "/api/v2/flags",
    "labels": "/api/v2/labels",
    "me": "/api/v2/me",
    "notificationEndpoints": "/api/v2/notificationEndpoints",
    "notificationRules": "/api/v2/notificationRules",
    "orgs": "/api/v2/orgs",
    "plugins": "/api/v2/telegraf/plugins",
    "query": {
        "analyze": "/api/v2/query/analyze",
        "ast": "/api/v2/query/ast",
        "self": "/api/v2/query",
        "suggestions": "/api/v2/query/suggestions"
    },
    "restore": "/api/v2/restore",
    "scrapers": "/api/v2/scrapers",
    "setup": "/api/v2/setup",
    "signin": "/api/v2/signin",
    "signout": "/api/v2/signout",
    "sources": "/api/v2/sources",
    "swagger": "/api/v2/swagger.json",
    "system": {
        "debug": "/debug/pprof",
        "health": "/health",
        "metrics": "/metrics"
    },
    "tasks": "/api/v2/tasks",
    "telegrafs": "/api/v2/telegrafs",
    "users": "/api/v2/users",
    "variables": "/api/v2/variables",
    "write": "/api/v2/write"
}

The drawback of this solution is that no other docker service can be exposed over the /api path as it is currently used by the influxdb traefik label rule

traefik.http.routers.influxdb.rule: PathPrefix(`/influxdb`) || PathPrefix(`/api`)

Maybe someone can help figure out how to run the influxdb api in a subpath location.

@robertohdzrz
Copy link

As an alternative to the solution provided by @arun-prakash-fokus (thank you a lot!), here are the needed steps to reproduce the same approach in k8s environment using Traefik (v2.9.6), plugin-rewritebody middleware and StripPrefix middleware.

  1. Add plugin-rewritebody to Traefik Static Configuration, e.g. as CLI args (as stated in https://plugins.traefik.io/plugins) and restart Traefik instance:
--experimental.plugins.plugin-rewritebody.modulename=github.com/traefik/plugin-rewritebody
--experimental.plugins.plugin-rewritebody.version=v0.3.1
  1. Create both middlewares as Kubernetes CRDs.
apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: influxdb-strip
  namespace: my-namespace
spec:
  stripPrefix:
    prefixes:
      - /influxdb
---
apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
    name: plugin-rewritebody
    namespace: my-namespace
spec:
    plugin:
        plugin-rewritebody:
            lastModified: true
            rewrites:
                - regex: src="/
                  replacement: src="/influxdb/
                - regex: href="/
                  replacement: href="/influxdb/
                - regex: data-basepath="
                  replacement: data-basepath="/influxdb/
                - regex: n.p="/"
                  replacement: n.p="/influxdb/"
                - regex: \)}/health`
                  replacement: )}/influxdb/health`
  1. Specify those middlewares (order is important) in Ingress annotations or IngressRoute CRD (both options are here presented). Using k8s Ingress:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: influxdb-ingress
  namespace: my-namespace
  annotations:
    traefik.ingress.kubernetes.io/router.tls.certresolver: default
    traefik.ingress.kubernetes.io/router.entrypoints: websecure
    traefik.ingress.kubernetes.io/router.middlewares: my-namespace-plugin-rewritebody@kubernetescrd, my-namespace-influxdb-strip@kubernetescrd
spec:
  tls:
  - hosts:
    - myhost.com
  rules:
  - host: myhost.com
    http:
      paths:
      - path: /influxdb
        pathType: Prefix
        backend:
          service:
            name: influxdb-svc
            port:
              number: 8086
      - path: /api
        pathType: Prefix
        backend:
          service:
            name: influxdb-svc
            port:
              number: 8086

or using IngressRoute k8s CRD:

apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: influxdb-ingressroute
  namespace: my-namespace
spec:
  entryPoints:
    - websecure
  routes:
    - match: Host(`myhost.com`) && PathPrefix(`/influxdb`) 
      kind: Rule
      middlewares: 
        - name: plugin-rewritebody
        - name: influxdb-strip
      services: 
        - name: influxdb-svc
          port: 8086
    - match: Host(`myhost.com`) && PathPrefix(`/api`) 
      kind: Rule
      middlewares: 
        - name: plugin-rewritebody
        - name: influxdb-strip
      services: 
        - name: influxdb-svc
          port: 8086
  tls:
    certResolver: default

And now you will be able to access InfluxDB UI through https://myhost.com/influxdb and InfluxDB API through https://myhost.com/influxdb/api/v2 or https://myhost.com/api/v2.

influx

influx2

Note that you might have to create a PVC for plugins storage in your Traefik instance and mount it as a volume, and also maybe to re-apply your InfluxDB instance to be reachable from your ingress/ingressroute correctly.

@bodak
Copy link

bodak commented Apr 6, 2023

Thanks @robertohdzrz! This works great.
For those who prefer to not use Traefik Hub and have it disabled, you can add the plugin as follows using Helm values:

  initContainers:
    - name: traefik-plugins-2
      image: k8s.gcr.io/git-sync/git-sync:v3.6.5
      args: ["-v", "6"]
      volumeMounts:
        - name: traefik
          mountPath: /plugins-local
      env:
        - name: GIT_SYNC_REPO
          value: https://github.com/traefik/plugin-rewritebody
        - name: GIT_SYNC_REV
          value: "v0.3.1"
        - name: GIT_SYNC_ROOT
          value: /plugins-local/src/github.com/traefik/
        - name: GIT_SYNC_BRANCH
          value: master
        - name: GIT_SYNC_LINK
          value: plugin-rewritebody
        - name: GIT_SYNC_PERMISSIONS
          value: "0777"
        - name: GIT_SYNC_ONE_TIME
          value: "true"
 ...
 additionalArguments:
    - "--experimental.localplugins.plugin-rewritebody.modulename=github.com/traefik/plugin-rewritebody"
 ...
 persistence:
    enabled: true
    name: traefik
    accessMode: ReadWriteOnce
    size: 256Mi
    path: /plugins-local
    annotations: {}

@kulmann
Copy link

kulmann commented May 14, 2023

@arun-prakash-fokus thank you for your example config, that helped me a lot! I'd like to add some additions to your proposed solution:

  1. with influxdb v2.7.1 the base path in the initially loaded .js file is stored in the variable o.p, not n.p. Seems like the var name just changed in the uglify step... had to adjust the rewritebody rule no. 3 accordingly:
traefik.http.middlewares.rewrite-foo.plugin.rewrite.rewrites[3].regex: o.p="/"
traefik.http.middlewares.rewrite-foo.plugin.rewrite.rewrites[3].replacement: o.p="/influxdb/"
  1. my setup is properly working without exposing port 8086. I configured my application to use the web entrypoint port exposed by traefik and then of course concatenated with my /influxdb path prefix.

  2. for anyone wondering how the folder structure in plugins-local needs to look like for traefik to find the plugin:

./plugins-local/src/github.com/traefik/plugin-rewritebody

Just put the content of the plugin-rewritebody repo into that folder and apply the plugin config like proposed by @arun-prakash-fokus then you're good to go with the plugin.

@jdeus
Copy link

jdeus commented Aug 30, 2023

Any news ? Seems like a basic feature to have ...

@gbravery
Copy link

gbravery commented Sep 4, 2023

OK, I have a stupid question - wondering if anyone can help.

Does the "work around" proposed by arun-prakash-fokus with the tweak proposed by kulmann still work?

As in my set up, it re-writes the html pages, but it's ignoring the javascript pages for some reason.

Influx is 2.7.1
Traefik is 2.10.4

I'm using chain middleware to join stripprefix and rewrite-body (tried the traefik and the packruler version):

  middlewares:
    influxdb-strip-prefix:
      stripprefix:
        prefixes:
          - /influxdb
    influxdb-rewrite:
      plugin:
        rewrite-gzip-body:
          lastModified: true
          loglevel: -1
          rewrites:
            - regex: src="/
              replacement: src="/influxdb/
            - regex: href="/
              replacement: href="/influxdb/
            - regex: data-basepath="
              replacement: data-basepath="/influxdb/
            - regex: n.p="/"
              replacement: n.p="/influxdb/"
            - regex: o.p = "/"
              replacement: o.p = "/influxdb/"
            - regex: \)}/health`
              replacement: )}/influxdb/health`
          monitoring:
            methods:
              - GET
            types:
              - text/html
              - text/javascript
    influxdb-chain:
      chain:
        middlewares:
          - influxdb-rewrite
          - influxdb-strip-prefix

@gbravery
Copy link

gbravery commented Sep 5, 2023

FWIW, I have managed to make this work - but not using packruler plugin.
I've also managed to redirect the API...

experimental:
  plugins:
    cookiePathPrefix:
      modulename: "github.com/SchmitzDan/traefik-plugin-cookie-path-prefix"
      version: "v0.0.3"
    rewrite-body:
      moduleName: "github.com/traefik/plugin-rewritebody"
      version: "v0.3.1
      
http:
  routers:
    household_influxdb:
      rule: Host(`my-host`) && ( PathPrefix(`/influxdb`) || PathPrefix(`/influxdb/`))
      service: household-influxdb
      entrypoints:
        - "web"
      middlewares: influxdb-cookie-path, influxdb-rewrite2, influxdb-strip-prefix
      
  middlewares:
    influxdb-cookie-path:
      plugin:
        cookiePathPrefix:
          prefix: "influxdb"
    influxdb-strip-prefix:
      stripprefix:
        prefixes:
          - /influxdb
    influxdb-rewrite2:
      plugin:
        rewrite-body:
          lastModified: true
          rewrites:
            - regex: src="/
              replacement: src="/influxdb/
            - regex: href="/
              replacement: href="/influxdb/
            - regex: data-basepath="
              replacement: data-basepath="/influxdb/
            - regex: n.p="/"
              replacement: n.p="/influxdb/"
            - regex: o.p="/"
              replacement: o.p="/influxdb/"
            - regex: /api/
              replacement: /influxdb/api/
            - regex: api/v2/query
              replacement: influxdb/api/v2/query
            - regex: \)}/health`
              replacement: )}/influxdb/health`

This isn't extensively tested - but I have made sure I can login, see data, etc.
There might be a better way of writing the regex too - the first /api/ covered a lot of the calls, but there was a specific hidden one that used api/v2/query. However, the /api/ is a bit to "general" and not targeted very well.

FWIW, I still think it would be better if InfluxDB had this built in!

@fichte
Copy link

fichte commented Oct 6, 2023

the following worked for us, we are deploying a docker stack with influxdb included

influxdb is internally available at http://influxdb:8086

externally via for example https://some.domain/influxdb

working location config for nginx:

location /influxdb/ {
    add_header Expect-CT "enforce, max-age=21600" always;
    add_header Permissions-Policy "camera=(), fullscreen=(), geolocation=(), microphone=(), payment=(), usb=()" always;
    add_header Referrer-Policy "strict-origin" always;
    add_header Strict-Transport-Security max-age=63072000 always;
    add_header X-Content-Type-Options nosniff always;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Xss-Protection "1; mode=block" always;
    set $influxdb_upstream influxdb:8086;
    rewrite ^/influxdb$ /influxdb/ permanent;
    rewrite ^/influxdb/(.*)$ /$1 break;
    proxy_cookie_path ~*^/api /influxdb/api;
    proxy_connect_timeout 600s;
    proxy_http_version 1.1;
    proxy_pass http://$influxdb_upstream;
    proxy_read_timeout 600s;
    proxy_send_timeout 600s;
    proxy_set_header Authorization $http_authorization;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $http_host;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto https;
    proxy_set_header X-Real-IP $remote_addr;
    sub_filter '<base href="/">' '<base href="/influxdb/">';
    sub_filter 'src="/' 'src="/influxdb/';
    sub_filter 'href="/' 'href="/influxdb/';
    sub_filter 'data-basepath="' 'data-basepath="/influxdb/';
    sub_filter 'n.p="/"' 'n.p="/influxdb/"';
    sub_filter 'o.p="/"' 'o.p="/influxdb/"';
    sub_filter '/api/' '/influxdb/api/';
    sub_filter 'api/v2/query' 'influxdb/api/v2/query';
    sub_filter '/health`' '/influxdb/health`';
    sub_filter_types text/css text/javascript application/javascript application/json;
    sub_filter_once off;
    modsecurity_rules '
      SecRuleEngine Off
    ';
  }

@ateska
Copy link

ateska commented Oct 6, 2023

Reducted version of above NGINX config from @fichte :

location /influxdb {
	rewrite ^/influxdb$ /influxdb/ permanent;
	rewrite ^/influxdb/(.*) /$1 break;
	proxy_pass http://upstream-influxdb;
	proxy_cookie_path ~*^/api /influxdb/api;
	proxy_set_header Authorization $http_authorization;
	proxy_set_header Host $http_host;
	proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
	proxy_set_header X-Forwarded-Proto https;
	proxy_set_header X-Real-IP $remote_addr;
}

Works for us - so far - on v2.7.1 of InfluxDB, with UI compiled to use BASE_PATH=/influxdb/ui and API_BASE_PATH=/influxdb.

Thank you!!!

@Tux12Fun
Copy link

@fichte
Your solution works for me but Dashborards are not viewable on my nginx. Do you also have problems if you create a dashboard and view this Dashboard?

@gbravery
Copy link

gbravery commented Oct 14, 2023 via email

@R4to0
Copy link

R4to0 commented Dec 5, 2023

@fichte solution so far works for me. Had to force disable nginx proxy caching in my instance.

@smehl
Copy link

smehl commented Jan 31, 2024

@fichte , @gbravery

Sorry, I didn't try that. I can take a look next week though.Sent from Outlook for Android

Have you found a solution? I am struggling with the same problem - some redirect doesn't seem to work for the dashboards. I am getting a "404: Page Not Found"; it seems like the nginx configuration redirects to a path /influxdb/influxdb/orgs (which obviously doesn't exist)

@alv000h
Copy link

alv000h commented Feb 2, 2024

Hi all!

this is a working nginx config (still testing, but looks ok)
thanks to @memetb and many others in this issue :)

location = /influx/env.js {
    # webpack process.env.* injection
    add_header Content-Type application/javascript;
    return 200 "var prefix='/influx/'; process = {'env' : {'STATIC_PREFIX':prefix,'API_PREFIX':prefix, 'BASE_PATH': prefix, 'API_BASE_PATH':prefix}};";
}
location /influx/ {
    rewrite ^/influx$ /influx/ permanent;
    rewrite ^/influx/(.*) /$1 break;
    proxy_cookie_path ~*^/api /influx/api;
    proxy_set_header Authorization $http_authorization;
    #proxy_set_header Referer $influx_referer;
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    #proxy_set_header X-Forwarded-Prefix /influx;
    # inject environment vars for front-end webpack
    sub_filter '</head>' '<script type="text/javascript" src="/influx/env.js"></script></head>';
    # mokey patch html things...
    sub_filter '<base href="/">' '<base href="/influx/">';
    sub_filter 'src="/' 'src="/influx/';
    sub_filter 'href="/' 'href="/influx/';
    sub_filter 'data-basepath="' 'data-basepath="/influx/';
    sub_filter 'n.p="/"' 'n.p="/influx/"';
    sub_filter 'o.p="/"' 'o.p="/influx/"';
    sub_filter '/api/' '/influx/api/';
    sub_filter 'api/v2/query' 'influx/api/v2/query';
    sub_filter '/health`' '/influx/health`';
    sub_filter_types text/css text/javascript application/javascript application/json;
    sub_filter_once off;
    proxy_pass http://influx:8086;
}

@RavilN
Copy link

RavilN commented Feb 5, 2024

I tried this configuration, and it works!
Thank you, alv000h!

linuxmaniac added a commit to linuxmaniac/home-ops that referenced this issue Feb 20, 2024
* traefik: add needed plugins to deal with influxdb
  not able to work properly in path /influxdb

> influxdata/influxdb#15721
linuxmaniac added a commit to linuxmaniac/home-ops that referenced this issue Feb 20, 2024
* traefik: add needed plugins to deal with influxdb
  not able to work properly in path /influxdb

> influxdata/influxdb#15721
@regnaio
Copy link

regnaio commented Apr 10, 2024

Is there a way to do this natively in InfluxDB 2?

For example, Grafana has a root_url configuration setting:

root_url = %(protocol)s://%(domain)s:%(http_port)s/subpath/

@gbravery
Copy link

Not currently, @regnaio - that’s why we’ve ended up with the convoluted NGINX and Traefik rules I am afraid.
The “bug” still stands. It obviously isn’t considered a high enough priority…

@regnaio
Copy link

regnaio commented Apr 11, 2024

@ateska , could you please describe how you compiled InfluxDB 2 and UI with BASE_PATH and API_BASE_PATH?

I also asked this here: https://community.influxdata.com/t/how-to-build-influxdb-2-with-custom-base-path-and-api-base-path/33890

@vpmartin
Copy link

vpmartin commented May 9, 2024

Tried both the hacky nginx config and the subdomain one with no luck yet — I'll stick with the port for now.

+1 for this issue, needs to be addressed, it's such a basic feature.

@schmavid
Copy link

Please, really just fix this! Forces us to create some nasty workarounds.
+1

@HamadiJABLOUN
Copy link

hello, please any news if it is prioritized?

@AJDurant
Copy link

AJDurant commented Sep 3, 2024

I've managed to use the following in Apache, based on #15721 (comment) above

  # InfluxDB
  ProxyPass "/influx"  "http://localhost:8086"
  ProxyPassReverse "/influx"  "http://localhost:8086"
  ProxyPreserveHost On

  <Location /influx>
    Require all granted

    # Proxy settings
    ProxyPassReverseCookiePath "/api" "/influx/api"

    # Monkey patch HTML things
    AddOutputFilterByType SUBSTITUTE text/html text/css text/javascript application/javascript application/json
    Substitute "s|<base href=\"/\">|<base href=\"/influx/\">|"
    Substitute "s|src=\"/|src=\"/influx/|"
    Substitute "s|href=\"/|href=\"/influx/|"
    Substitute "s|data-basepath=\"|data-basepath=\"/influx/|"
    Substitute "s|n.p=\"/\"|n.p=\"/influx/\"|"
    Substitute "s|o.p=\"/\"|o.p=\"/influx/\"|"
    Substitute "s|/api/|/influx/api/|"
    Substitute "s|api/v2/query|influx/api/v2/query|"
    Substitute "s|/health`|/influx/health`|"

    # Inject environment vars for front-end webpack
    Substitute "s|</head>|<script type=\"text/javascript\" src=\"/env.js\"></script></head>|"

    # Ensure substitute filters are applied correctly
    SubstituteMaxLineLength 10m
  </Location>

with env.js served directly from the server in the root.

var prefix='/influx/';
process = {'env' : {'STATIC_PREFIX':prefix,'API_PREFIX':prefix, 'BASE_PATH': prefix, 'API_BASE_PATH':prefix}};

@anhtu812
Copy link

thank @alv000h , but dashboard still not work it out 404

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area/ui area/2.x OSS 2.0 related issues and PRs wontfix
Projects
None yet
Development

No branches or pull requests