单页应用程序的简单命令行 http 服务器

Simple command-line http server for Single Page App

有多种one-liner HTTP server commands,例如最著名的可能是 python -m http.server。我正在寻找一个类似的命令,它将 运行 忽略文件路径并将所有路径发送到特定文件的服务器,例如如果您访问 /foo 或 /bar,它将从 index.html.

开始提供服务

并且理想情况下,对于典型的 Linux/MacOS 机器,尽可能减少安装麻烦。 (例如,python 和 http.server 将对许多用户开箱即用。)

它与 htaccess 规则 RewriteRule (.*) /index.html 提供的功能相同,但不需要设置 Apache。不确定这些单行服务器是否支持类似的东西,比如声明所有路径的默认文件的命令行参数。

#!/usr/bin/env node
const express = require('express');
const server = express();

server.all('/*', (_, res) => {
  // You would probably not want to hard-code this,
  // but make it a command line argument.
  res.sendFile(__dirname + '/index.html');
});

const port = 8000;
server.listen(port, () => {
  console.log('Server listening on port', port);
});

使文件可执行 (chmod +x) 并将其保存在您的 PATH 中的某个位置。

https://github.com/svenstaro/miniserve 只服务 index.html 你只需要 miniserve index.html。它是用 Rust 编写的,因此您不需要任何额外的依赖项。

Using php,命令行里有一个built in development server,超级好用

第一个示例,在当前文件夹中,仅提供文件 index.html at 127.0.0.1,端口8080:

php -S 127.0.0.1:8080 index.html

输出

PHP 7.2.24-0ubuntu0.18.04.1 Development Server started at Mon Dec 23 15:37:03 2019
Listening on http://127.0.0.1:8080
Document root is /home/nvrm
Press Ctrl-C to quit.

在这种情况下,只有文件 index.html 会在 http://127.0.0.1:8080

响应

此端口上的任何 http 调用都将重定向到 index.html


第二个示例将 整个当前文件夹 绑定到 localhost,端口 5555:

php -S localhost:5555 

输出:

PHP 7.2.24-0ubuntu0.18.04.1 Development Server started at Mon Dec 23 09:59:44 2019
Listening on http://localhost:5555
Document root is /home/nvrm
Press Ctrl-C to quit.

这将在地址 http://localhost:5555

提供 index.html

如果文件 index.php 存在,那么它将首先被提供(解释为 php)

提供(子)文件夹中的所有其他文件,例如 http://localhost:5555/css/style.css 也会响应,如果此文件夹和文件当然存在。 (否则响应错误404)


第三个例子,从任何地方运行,传入路径作为第三个参数。也可以使用本地 ip,通过这样做,文件可以在 整个本地网络 上使用。 示例本地 ip:192.168.1.23。 要检索我们的本地 ip,我们可以使用 ifconfig.

php -S 192.168.1.23:8080 ~/www

这将为端口 8080 上的主文件夹中的文件夹 www 提供服务:http://192.168.1.23:8080 网络上的每个人。


显然,我们可以运行许多不同端口上的许多服务器并行^ 对开发很有用,也可以在虚拟机、设备、手机等之间快速共享文件


或者。使用 0.0.0.0 作为 ip 地址监听所有接口。在某些情况下,这是唯一适用于本地网络中所有设备的命令。

php -S 0.0.0.0:5555 

然后使用本机ip为url:http://192.168.1.23:5555


为了能够关闭终端,但要保持服务器运行ning,我们可以使用nohup:

nohup php -S localhost:8080 &

然后杀掉它,快点:

fuser -k 8080/tcp 

最后一个示例,使用 主机名。 要从控制台检索机器主机名,unix 命令是 hostname.

php -S $(hostname):9999

将绑定到 http://<session_name>-<machine_name>:9999


可以只安装php的cli版本到运行这个(~4mo ).它包含在核心中。

sudo apt install php-cli

对于更高级的服务器用法,但配置简单,热烈推荐caddy server