简体   繁体   中英

How do I host a localhost on my server with Mac Terminal?

I've been hosting a localhost on my Mac with CSS, HTML, and JS. To do this i just navigate to my file with cd Desktop followed by cd filename , and then I do python -m SimpleHTTPServer 8000 to host my server on my localhost. I know that this only works for the person hosting the server, but I'd like to host it on my local network, so anyone that goes to localhost:8000 will see it. (I'm fine with it not being localhost:8000 , in fact, I'd love a custom name.)
Thank you

First of all, localhost is a "domain" name if you like. Most of the times it resolves to 127.0.0.1 which is the loopback ip address(eg points back to your computer). I am going to assume you are using python 2.x

So here we go:

#!/usr/bin/env python
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

addr = ("0.0.0.0", 8000) #host to everyone

serv = BaseHTTPServer.HTTPServer(addr, SimpleHTTPRequestHandler)

serv.serve_forever()

Save that to a python script and run with:

python myfile.py

If you are using python 3 then go with :

python3 -m http.server --bind 0.0.0.0 8000

Now for someone else to access your server through your local network, you have to give them your machine's ip. To do that run:

ifconfig |grep inet

You should get something alone the lines of:

inet 192.168.1.2 netmask 0xffffff00 etc etc

Now anyone on your local network can use your server by typing

192.168.1.2:8000 

in their browsers

One easy way to expose localhost to other people is using ngrok , available via brew install ngrok or that link. In your example above, running ngrok 8000 would allow other people to access the server you've got hosted. It's worth noting, obviously, that this isn't restricted to your local network!

Perhaps a better option (if all you're doing is hosting static HTML, CSS & JS) would be to set up a simple Apache instance. The default config should probably work just fine, and people could then access your page using your computer's local IP eg 192.168.0.10:8000 , or whatever port you set up.

EDIT: As the other answerer pointed out, SimpleHTTPServer will do everything Apache does... You just need to give people your machine's local IP!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM