Giter VIP home page Giter VIP logo

http-server's Introduction

GitHub Workflow Status (master) npm homebrew npm downloads license

http-server: a simple static HTTP server

http-server is a simple, zero-configuration command-line static HTTP server. It is powerful enough for production usage, but it's simple and hackable enough to be used for testing, local development and learning.

Example of running http-server

Installation:

Running on-demand:

Using npx you can run the script without installing it first:

npx http-server [path] [options]

Globally via npm

npm install --global http-server

This will install http-server globally so that it may be run from the command line anywhere.

Globally via Homebrew

brew install http-server

As a dependency in your npm package:

npm install http-server

Usage:

 http-server [path] [options]

[path] defaults to ./public if the folder exists, and ./ otherwise.

Now you can visit http://localhost:8080 to view your server

Note: Caching is on by default. Add -c-1 as an option to disable caching.

Available Options:

Command Description Defaults
-p or --port Port to use. Use -p 0 to look for an open port, starting at 8080. It will also read from process.env.PORT. 8080
-a Address to use 0.0.0.0
-d Show directory listings true
-i Display autoIndex true
-g or --gzip When enabled it will serve ./public/some-file.js.gz in place of ./public/some-file.js when a gzipped version of the file exists and the request accepts gzip encoding. If brotli is also enabled, it will try to serve brotli first. false
-b or --brotli When enabled it will serve ./public/some-file.js.br in place of ./public/some-file.js when a brotli compressed version of the file exists and the request accepts br encoding. If gzip is also enabled, it will try to serve brotli first. false
-e or --ext Default file extension if none supplied html
-s or --silent Suppress log messages from output
--cors Enable CORS via the Access-Control-Allow-Origin header
-o [path] Open browser window after starting the server. Optionally provide a URL path to open. e.g.: -o /other/dir/
-c Set cache time (in seconds) for cache-control max-age header, e.g. -c10 for 10 seconds. To disable caching, use -c-1. 3600
-U or --utc Use UTC time format in log messages.
--log-ip Enable logging of the client's IP address false
-P or --proxy Proxies all requests which can't be resolved locally to the given url. e.g.: -P http://someurl.com
--proxy-options Pass proxy options using nested dotted objects. e.g.: --proxy-options.secure false
--username Username for basic authentication
--password Password for basic authentication
-S, --tls or --ssl Enable secure request serving with TLS/SSL (HTTPS) false
-C or --cert Path to ssl cert file cert.pem
-K or --key Path to ssl key file key.pem
-r or --robots Automatically provide a /robots.txt (The content of which defaults to User-agent: *\nDisallow: /) false
--no-dotfiles Do not show dotfiles
--mimetypes Path to a .types file for custom mimetype definition
-h or --help Print this list and exit.
-v or --version Print the version and exit.

Magic Files

  • index.html will be served as the default file to any directory requests.
  • 404.html will be served if a file is not found. This can be used for Single-Page App (SPA) hosting to serve the entry page.

Catch-all redirect

To implement a catch-all redirect, use the index page itself as the proxy with:

http-server --proxy http://localhost:8080?

Note the ? at the end of the proxy URL. Thanks to @houston3 for this clever hack!

TLS/SSL

First, you need to make sure that openssl is installed correctly, and you have key.pem and cert.pem files. You can generate them using this command:

openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem

You will be prompted with a few questions after entering the command. Use 127.0.0.1 as value for Common name if you want to be able to install the certificate in your OS's root certificate store or browser so that it is trusted.

This generates a cert-key pair and it will be valid for 3650 days (about 10 years).

Then you need to run the server with -S for enabling SSL and -C for your certificate file.

http-server -S -C cert.pem

If you wish to use a passphrase with your private key you can include one in the openssl command via the -passout parameter (using password of foobar)

e.g. openssl req -newkey rsa:2048 -passout pass:foobar -keyout key.pem -x509 -days 365 -out cert.pem

For security reasons, the passphrase will only be read from the NODE_HTTP_SERVER_SSL_PASSPHRASE environment variable.

This is what should be output if successful:

Starting up http-server, serving ./ through https

http-server settings:
CORS: disabled
Cache: 3600 seconds
Connection Timeout: 120 seconds
Directory Listings: visible
AutoIndex: visible
Serve GZIP Files: false
Serve Brotli Files: false
Default File Extension: none

Available on:
  https://127.0.0.1:8080
  https://192.168.1.101:8080
  https://192.168.1.104:8080
Hit CTRL-C to stop the server

Development

Checkout this repository locally, then:

$ npm i
$ npm start

Now you can visit http://localhost:8080 to view your server

You should see the turtle image in the screenshot above hosted at that URL. See the ./public folder for demo content.

http-server's People

Contributors

adunkman avatar avianflu avatar bigbluehat avatar boarwell avatar boramalper avatar chris--jones avatar coltonherrod avatar danielmahon avatar dependabot[bot] avatar fotoverite avatar glls avatar indexzero avatar jbergens avatar jfhbrook avatar katowulf avatar luk- avatar marak avatar mbrowne avatar michaelsbradleyjr avatar michalcz avatar mmalecki avatar ratcoder avatar smileart-levelup avatar sowmiyamuthuraman avatar sqlwwx avatar thornjad avatar wayiam avatar wmertens avatar xmader avatar zbynek avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

http-server's Issues

Warnings and the server doesn't start

I'm not sure what's going on. I tried reinstalling http-server, but it still isn't working. When I run http-server, it says

Starting up http-server, serving ./ on port: 8080
Hit CTRL-C to stop the server

But if I go to http://localhost:8080/, I get a "No Data Received" error in Chrome.

When I installed and reinstalled http-server, I got this error.
screen shot 2014-05-11 at 8 54 31 pm

Option to append trailing forward slash?

Would be nice if there was an option to auto-append a trailing / to the URL (i.e. redirect to the URL with / appended) in the case of directories where http-server has loaded index.html.

Apache and some other web servers do that, and sometimes folks will write their .html files with the expectation that a sever will perform such redirects.

gzip support

Would it be possible to have an option for gzip/deflate compression?

pushState support

Any way to make this work with [backbone's] pushState? IE:

http://localhost:8000/noun/:id

should be interchangable with

http://localhost:8000#noun/:id

s/vendor/node_modules/g

Then you can get rid of this:

require.paths.unshift(require('path').join(__dirname, '..', 'vendor'));

What does the autoIndex option do?

Does it index directories without a restart of the app? Does marking it False mean that modifying a directory will not be recognized without a restart of the app? Please explain. Thanks!

can't disable autoIndex

Is it possible to disable autoIndexing?

> http-server -h
...
  -i                 Display autoIndex [true]

> http-server -i false # does not work

Am I passing -i the wrong value?

display IP address on server start

Every time I run http-server, the second thing I do is open another terminal tab and type ifconfig -a, and find the IP address I'll use to connect to from other (usually mobile) devices. It would be convenient if http-server offered me that info automatically, if that's even possible w node.

starting http-server doesn't work at all with latest code

I jsut did a npm update -g and http-server command doesn't work anymore.
I have node 10.28 x86 on a windows 7 64 bit machine .

C:\Users\Ovidiu\AppData\Roaming\npm\node_modules\http-server\bin\http-server:43
    if (err) throw err;
                   ^
Error: listen EACCES
    at errnoException (net.js:904:11)
    at Server._listen2 (net.js:1023:19)
    at listen (net.js:1064:10)
    at net.js:1146:9
    at dns.js:72:18
    at process._tickCallback (node.js:419:13)
    at Function.Module.runMain (module.js:499:11)
    at startup (node.js:119:16)
    at node.js:906:3

can someon else also reproduce this issue ?

Use nconf for configuration management

We should replace the current argument parsing with optimist and replace it with nconf.

This will allow http-server to be configured via the command line, or a config.json file, or any other transport nconf supports.

pls can you add -w watch option to this amazing module

it would be really nice to have watch and reload option for http-server , i use this package all the time and what bugs me is i have to refresh broiwer after making changes all the time.

I wish this had -w watch option which would watch current directory and reload after changes are detected , i know this can be done with other plugins but i wish http-server server had this funtionality.

Thanks

Cannot start http-server

Hey guys,
I got an issue with my http-server. I am using Ubuntu OS, I install http-server via sudo npm install http-server -g.
I have installed successful but when I run 'http-server' command, it didn't work, like this:
noiz@Noiz:$ http-server
noiz@Noiz:
$
I dont know why? Help me please.
Thanks,

Version 0.7.1 and 0.7.0 is not working on Windows 7 64

I always recommend http-server for designers etc... it's very easy to use on any folder.

But a friend on Windows 7 64bits can't use it and I don't know why, the server start fine (but using https on 0.7.0 and http in 0.7.1) but we can't navigate in the browser, the browser just show that the page can't be loaded.

I don't know if there's some debug file in somewhere in windows, if it exist I can check it out and share here for debug.

I downgraded to version 0.6.1 and everything worked fine!

Add support for mod_rewrite equivalent

Any plans to add support for rewriting urls (like apache mod_rewrite)? I'd like to be able to include links in my source like /link/to/example instead of /link/to/example.html

Add basic auth

It would be nice if we could specify --user and --pass to require basic authentication for the server. Obviously this shouldn't be considered secure, but it would be a nice feature for basic protection.

https support

It'd be nice if it'd be a CLI option, and if it'd auto-generate a self-signed cert. Some things need https.

http uri by default not https

bug:
var uri = [ssl ? 'http' : 'https', '://', host, ':', port].join('');

fix:
var uri = [ssl ? 'https' : 'http', '://', host, ':', port].join('');

Relative URL's don't work properly

According to http://www.w3.org/TR/WD-html40-970917/htmlweb.html#h-5.1.3 a relative URL should resolve to the current directory. However it seems the server ignores the current directory and appends directly to the domain. This is problematic for relative links in html.

For example:

on http://domain/page/index.html

<a href='text.html'>should resolve to http://domain/page/test.html. However currently it resolves to http://domain/test.html.

Investigation shows that this works properly with just union and ecstatic.

accept --hsts flag

Would you accept a pull request to accept an --hsts command line flag, which would implement this logic (from https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security ):

protected void Application_BeginRequest(Object sender, EventArgs e)
{
  switch (Request.Url.Scheme)
  {
    case "https":
      Response.AddHeader("Strict-Transport-Security", "max-age=31536000");
      break;
    case "http":
      var path = "https://" + Request.Url.Host + Request.Url.PathAndQuery;
      Response.Status = "301 Moved Permanently";
      Response.AddHeader("Location", path);
      break;
  }
}

Basic logging on console

I was using Python's SimpleHTTPServer before, and I got some output when the server was running:

python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...
1.0.0.127.in-addr.arpa - - [16/Mar/2013 17:57:02] "GET / HTTP/1.1" 200 -
1.0.0.127.in-addr.arpa - - [16/Mar/2013 17:57:02] "GET /js/libs/backbone/backbone.js HTTP/1.1" 200 -

It would be great to see some basics 200, 404, ... in the console. Is this planned? Thanks!

Can't update http-server to 0.6.1

I was hit by the http-server 0.6.0 error so I wanted to update it but I can't. I get the following output in the terminal:

$ npm -g update http-server
info trying registry request attempt 1 at 19:45:53
http GET https://registry.npmjs.org/http-server/latest
http 304 https://registry.npmjs.org/http-server/latest
info trying registry request attempt 1 at 19:45:55
http GET https://registry.npmjs.org/http-server
http 304 https://registry.npmjs.org/http-server
npm http GET https://registry.npmjs.org/http-server/-/http-server-0.6.1.tgz
npm http 404 https://registry.npmjs.org/http-server/-/http-server-0.6.1.tgz
npm ERR! fetch failed https://registry.npmjs.org/http-server/-/http-server-0.6.1.tgz

Indeed, the URL https://registry.npmjs.org/http-server/-/http-server-0.6.1.tgz returns:

{
    "error":"not_found",
    "reason":"Document is missing attachment"
}

The URL for the previous version, https://registry.npmjs.org/http-server/-/http-server-0.6.0.tgz, works, but this version has a critical issue making it not run.

option to set response headers, specially for CORS

I'm developing locally and need multiple servers running on different ports, so XHR doesn't work (different port is also blocked by same-origin policy).

I want to simply add Access-Control-Allow-Origin: * to the response header but other users might have different needs so I'm thinking on a new option to set the custom headers:

http-server --header 'Access-Control-Allow-Origin: *; X-Foo: Bar; X-Lorem: Ipsum; ...'

and also and alias for Access-Control-Allow-Origin: *:

http-server --cors

If you agree I can implement this feature and ask for a pull request next week.

How to monitor http-server

Going to try to use http-server for production static site. Would be nice if there was some docs on how to use monit or forever to keep this service up. Any hints or tips for some sort of monitoring would be really helpful for me!!! Thanks Awesome project.

Show /404.html on 404

The place to add this to the vendored node-static is probably somewhere in here:

<https://github.com/nodejitsu/http-server/blob/master/vendor/node-static/lib/node-static.js#L66>

Alternately, modifying the finish function itself (wherever it is) may also work.

Accessing http-server from global

There are some issues when trying to use the global install.

module.js:340
throw err;
^
Error: Cannot find module '/Users/vcao/bin/http-server'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3

Unable to start the server

I'm not able to start the server. I keep hitting the following error.

http-server -p 9999

/usr/local/lib/node_modules/http-server/bin/http-server:21
" -o Open browser window after staring the server",
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Unexpected string
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3

Please help me with this.

How to use with "forever"

Could someone please explain how to launch this using the "forever" script on Windows. Normally one would type "forever start script.js [script options]" but I'm having trouble finding the actual script. I installed it using the "-g" global switch on npm and it runs fine from the command line by just typing "http-server" but I can't get it to work with "forever".

Use inside of node example

Is there an example of using this inside of node, where I can write other code, like mongo or websockets?

Like
server=require (http-server).

server.server(directory)

?

allow different cache times for different urls

Currently http-server allows you to configure the "cache-control: max-age" value for all urls. But often you want a short max-age for e.g. /{index.html} and a long max-age for urls to versioned assets like /styles/f35ac111.main.css.

Would you accept a patch to allow specifying different max-ages for different urls? (This could be implemented most generally by matching the request url against one or more configurable regexes which map to corresponding max-ages, for instance. But if it's simpler, just giving the long cache time to everything that isn't in the root directory, or every asset with a name like a1b2c3d4.filename.ext would probably work for many use cases.)

Does not like Range header

Ordinarily I'd investigate this but I don't have time. If this is not supposed to be a feature then kindly close the issue.

$ aria2c -x 4  --http-proxy="http://127.0.0.1:8080/" http://server:8000/big-image.dmg
# Note the previous ~16% was from another server, aria2c is auto-continuing
[#4bd02b 64MiB/378MiB(16%) CN:4 DL:0B]
03/12 14:12:31 [ERROR] CUID#8 - Download aborted. URI=http://server:8000/big-image.dmg
Exception: [AbstractCommand.cc:315] errorCode=8 URI=http://server:8000/big-image.dmg
  -> [HttpResponse.cc:110] errorCode=8 Invalid range header. Request: 232783872-315621375/396531151, Response: 0-396531150/396531151

List files in directory?

Is there a way using this to get a list of the files in a directory? I have a folder of images and I'd like the server to tell the client app what they are. Only thing I've thought of is making an ajax request to the folder's directory listing page and parsing them out, but that seems less than ideal....

Add support for a configuration file (.httpserverrc?)

I use http-server to develop multiple projects on my local machine. I want each project to be launched from a different port - so that I can use Chrome DevTools' Workspaces for editing with no problems (DevTools does "per hostname" binding between remote files and local files).

Currently http-server does not allow to load configuration options from a file so I need to manually provide and remember each port for each of my projects.

My proposition is to have a .httpserverrc file (like .bowerrc or .jshintrc) which will allow to store the configuration in a JSON format.

Related issue: #24

Support HTML5 push-state

How can I use angularjs' html5Mode true.

Need to do some server configuration. What needs to be done? Where?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.