Skip to content

Live Server without file extension in URL

By default Live Server will require you to append the extension of the file in the URL; without the extension, you get the Cannot GET message

However, there's ways around this, so that common webpage files like .htm, .html, .php ... etc can be omitted while still allowing Live Server to serve the page correctly.

index.js

We need to change the logic of Live Server so that it would test for different types of extensions when none is provided. This logic can be modified in the file index.js located here:

Linux:

~/.vscode/extensions/ritwickdey.liveserver-5.7.9/node_modules/live-server/index.js
Windows:
%userprofile%\.vscode\extensions\ritwickdey.liveserver-5.7.9\node_modules\live-server\index.js

Note

ritwickdey.liveserver-5.7.9 includes the version number of your install, so it may or may not be 5.7.9

in this file, look for var reqpath = isFile ? "" : url.parse(req.url).pathname;

index.js
    return function (req, res, next) {
        if (req.method !== "GET" && req.method !== "HEAD") return next();
        var reqpath = isFile ? "" : url.parse(req.url).pathname;
        var hasNoOrigin = !req.headers.origin;
        var injectCandidates = [
            new RegExp("</body>", "i"),
            new RegExp("</svg>"),
            new RegExp("</head>", "i")
        ];

where you will add in the following code on the next line

        //INJECTION BEGIN
        const ext = ["", ".htm", ".html", ".shtml", ".xhtml", ".php"];
        for (let i = 0; i < ext.length; i++) {
            if (fs.existsSync(root.slice(0, -1) + reqpath + ext[i], "utf8")) {
                reqpath += ext[i];
                break;
            }
        }
        //INJECTION END
The order of the array of ext tests the extension type one by one until it finds the one where a file exists. The order, and extension types can be modified as needed.

Note

"" simply tests the address as is, so it the user provided the file extension, it'll be loaded directly.

With the code block added in, it should look something like this:

index.js
    return function (req, res, next) {
        if (req.method !== "GET" && req.method !== "HEAD") return next();
        var reqpath = isFile ? "" : url.parse(req.url).pathname;
        //INJECTION BEGIN
        const ext = ["", ".htm", ".html", ".shtml", ".xhtml", ".php"];
        for (let i = 0; i < ext.length; i++) {
            if (fs.existsSync(root.slice(0, -1) + reqpath + ext[i], "utf8")) {
                reqpath += ext[i];
                break;
            }
        }
        //INJECTION END
        var hasNoOrigin = !req.headers.origin;
        var injectCandidates = [
            new RegExp("</body>", "i"),
            new RegExp("</svg>"),
            new RegExp("</head>", "i")
        ];

Then simply save the file and restart the live server.

Reference: https://github.com/ritwickdey/vscode-live-server/issues/496#issuecomment-1366824437