侧边栏壁纸
博主头像
nivnek博主等级

道阻且长,行则将至

  • 累计撰写 21 篇文章
  • 累计创建 27 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

Restrict access to certain path

kenvin
2024-01-25 / 0 评论 / 101 点赞 / 1452 阅读 / 3290 字

Restrict access to certain path

In Caddy, you can restrict access to certain paths based on the client's IP address using the remote_ip matcher and the handle directive. Here is an example Caddyfile configuration that allows only specific IP addresses to access the /admin path:

example.com {
    @admin {
        path /admin*
        remote_ip 192.0.2.1 192.0.2.2
    }

    handle @admin {
        # Your directives for the admin area, e.g., reverse_proxy, file_server, etc.
        # ...
    }

    handle {
        # Directives for the rest of your site
        # ...
    }
}

In this configuration:

  • @admin is a named matcher that matches requests for paths beginning with /admin and originating from the IP addresses 192.0.2.1 and 192.0.2.2.

  • The handle @admin block will only apply to requests that match the @admin conditions. You can place any directives you want inside this block to handle the requests for the admin area.

  • The handle block without a matcher will catch all other requests that do not match the @admin conditions.

If a client with an IP address that is not listed tries to access the /admin path, they will receive a 404 Not Found response by default because there are no directives outside the handle blocks that apply to the /admin path.

For more advanced access control, you might want to look into using the basicauth directive to require a username and password for the admin area or explore plugins that provide more sophisticated access control mechanisms.

When you have many path route to different backend serivce, you should write the caddy file as following

example.com {
    @admin {
        path /admin*
        remote_ip 192.0.2.1 192.0.2.2
    }
    route /admin* {
    handle @admin {
        # Your directives for the admin area, e.g., reverse_proxy, file_server, etc.
        # ...
    }

    handle {
        # Directives for the rest of your site
        # ...
    }
   }
   route /path1* {
    # Your directives to backend service A
    # ...
   }
   route /path2* {
    # Your directives to backend service B
    # ...
   }
}

The handle directive is kind of similar to the location directive from nginx config, The route Evaluates a group of directives literally and as a single unit.

Refer:

101

评论区