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

mah*_*off 4 command-line http httpserver single-page-application

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

理想情况下,对于典型的 Linux/MacOS 机器,尽可能少安装麻烦。(例如,pythonhttp.server对许多用户来说都是开箱即用的。)

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

NVR*_*VRM 5

使用php,有一个来自命令行的内置开发服务器,非常有用。

第一个示例,在当前文件夹中, index.html 提供127.0.0.1, port处的文件8080

php -S 127.0.0.1:8080 index.html
Run Code Online (Sandbox Code Playgroud)

输出

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.
Run Code Online (Sandbox Code Playgroud)

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

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


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

php -S localhost:5555 
Run Code Online (Sandbox Code Playgroud)

输出:

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.
Run Code Online (Sandbox Code Playgroud)

这将index.html在地址 http://localhost:5555 上提供服务

如果文件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
Run Code Online (Sandbox Code Playgroud)

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


显然,我们可以在许多不同的端口上并行运行许多服务器^ 对开发人员非常有用,而且还可以在虚拟机、设备、电话等之间快速共享文件。


或者。使用0.0.0.0ip 地址侦听所有接口。在某些情况下,这是在本地网络中的每个设备上都能很好地服务的唯一命令。

php -S 0.0.0.0:5555 
Run Code Online (Sandbox Code Playgroud)

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


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

nohup php -S localhost:8080 &
Run Code Online (Sandbox Code Playgroud)

然后杀死它,快速:

fuser -k 8080/tcp 
Run Code Online (Sandbox Code Playgroud)

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

php -S $(hostname):9999
Run Code Online (Sandbox Code Playgroud)

将绑定到类似的东西 http://<session_name>-<machine_name>:9999


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

sudo apt install php-cli
Run Code Online (Sandbox Code Playgroud)

对于更高级的服务器用法,但易于配置,我建议使用caddy 服务器