You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Javalin中移除URL末尾的.html后缀?

Does Javalin support removing .html suffix for static routes?

Absolutely! Javalin can replicate that Nginx-style behavior where URLs like mysite.com/login map to login.html—it just doesn’t have a one-click toggle in StaticFileConfig, so you’ll need to use a couple of its flexible routing features to pull it off.

Here are two reliable approaches:

1. Modify the request path with a before hook (cleanest solution)

This method tweaks the incoming request path before it reaches the static file handler, so the static file system automatically finds the corresponding .html file while keeping the user-facing URL clean.

Javalin app = Javalin.create(config -> {
    // Configure your static files first
    config.staticFiles.add(staticFile -> {
        staticFile.directory = "/public"; // Your static files folder
        staticFile.hostedPath = "/";
    });
}).start(8080);

// Add a before hook to adjust paths without extensions
app.before(ctx -> {
    String path = ctx.path();
    // Skip API routes, paths with existing extensions, and directories
    if (!path.startsWith("/api/") && !path.contains(".") && !path.endsWith("/")) {
        ctx.path(path + ".html");
    }
});

This way, when a user visits mysite.com/login, the hook quietly changes the internal path to /login.html, which your static file handler serves up without redirecting the user.

2. Create a catch-all route to serve .html files directly

If you prefer more explicit control, you can set up a catch-all route that checks for the existence of a corresponding .html file and serves it directly:

Javalin app = Javalin.create(config -> {
    config.staticFiles.add(staticFile -> {
        staticFile.directory = "/public";
        staticFile.hostedPath = "/";
    });
}).start(8080);

// Catch all paths without extensions
app.get("{path}", ctx -> {
    String filePath = "/" + ctx.pathParam("path") + ".html";
    try {
        // Serve the file if it exists
        ctx.serveFile(filePath);
    } catch (FileNotFoundException e) {
        // Fallback to 404 if no matching file exists
        ctx.status(404).result("Page not found");
    }
});

Just make sure this route is registered after your API routes (if any) so those don’t get caught by the catch-all.

Key Notes

  • Always exclude API routes from these rules (like the /api/ check in the first example) to avoid breaking your backend endpoints.
  • If you have nested directories in your static files (e.g., mysite.com/about/team mapping to about/team.html), both methods will work as long as your file structure matches the URL structure.

内容的提问来源于stack exchange,提问作者jchernin4

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 10:35:41