前言
冷知识:Windows内置了一个极其轻量的HTTP服务器。不需要配置IIS,也无需额外安装Python、Apache、Nginx等软件,仅用一行命令就能启动。这对于无法联网或禁止安装第三方软件的隔离环境来说,好处不必多言。
启动服务器
假设你要在localhost:8000开启HTTP服务。那么此时请启动PowerShell,切换到服务的根目录(你站点资源的所在目录),并复制粘贴以下命令执行:
$h = [System.Net.HttpListener]::new(); $h.Prefixes.Add('http://localhost:8000/'); $h.Start(); Write-Host 'Serving http://localhost:8000'; Start-Process 'http://localhost:8000/index.html'; while ($h.IsListening) { $c=$h.GetContext(); $req=$c.Request; $path=Join-Path (Get-Location) ($req.Url.LocalPath.TrimStart('/')); if (Test-Path $path -PathType Leaf) { $bytes=[IO.File]::ReadAllBytes($path); $c.Response.StatusCode=200 } else { $bytes=[Text.Encoding]::UTF8.GetBytes('Not Found'); $c.Response.StatusCode=404 } $c.Response.OutputStream.Write($bytes,0,$bytes.Length); $c.Response.Close() }
一些说明
- 在这段命令中:
Start-Process 'http://localhost:8000/index.html';
用于启动默认浏览器并访问http://localhost:8000/index.html。如无需要可以删除。
-
用该命令启动的服务器不会自动将
index.html等作为默认主页返回。因此访问时需要手动指定访问资源。 -
如果你用的不是PowerShell而是Windows命令提示符或者bat批处理文件,那么服务器启动命令如下:
powershell -Command "<上面那一大串PS命令>"
