Caddy handle subdirectory api

5.3k Views Asked by At

I am looking to convert nginx config file to caddy with multiple sub path api configs.

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name example.com;
    root /usr/local/var/www/example/ui;
    index index.html index.htm;
    
    location /api/ {
            proxy_pass http://localhost:9000/api/;
            proxy_redirect off;
            proxy_buffering off;
            proxy_set_header Host $host;
    }
    location /usermgmt/ {
            proxy_pass http://127.0.0.1:9000/;
            proxy_redirect off;
            proxy_buffering off;
    }
    location /integrations/ {
            proxy_pass http://127.0.0.1:9003/;
            proxy_redirect off;
            proxy_buffering off;
            proxy_set_header Host $host;
    }

I tried with caddy reverse_proxy but not working. Api request should go example.com/api instead of example.com/integration/api through proxy. Please help me how to solve this problem.

1

There are 1 best solutions below

0
On

You can do this using the handle directive.

example.com {
   handle /api/ {
     reverse_proxy localhost:9000
   }
   handle /usermgmt/ {
     reverse_proxy localhost:9003
   }
   root /usr/local/var/www/
   handle {
       file_server
   }
}

This works because handle is mutually exclusive. Documentation here: https://caddyserver.com/docs/caddyfile/directives/handle