Sometimes I just need a simple and fast webserver to test my sites, html pages and CGI scripts but I don't want to install a full webserver like Apache or Nginx.
The fastest way to run a local web server is typing this in the command line:
python -m SimpleHTTPServer
This will display "Serving HTTP on 0.0.0.0 port 8000 ..." and you'll be able to see the current directory and files when accessing your own computer:
You can run multiple web servers at once, but each must be in a distinct port or you'll get the error "Address already in use". Just put the desired port number after the python command (e.g.: how to run python webserver in port 8001):
python -m SimpleHTTPServer 8001
How to run a web server that runs CGI
If you want to run a webserver that also runs CGI, then run:
python -m CGIHTTPServer
The CGI scripts should be in the "cgi-bin" folder. So you need to run the python command in a directory before "cgi-bin" dir.
I am using cygwin command line under Windows 7 and I got an error when running "python -m CGIHTTPServer":
127.0.0.1 - - [30/Aug/2014 19:51:59] "GET /cgi-bin/tmp.pl HTTP/1.1" 200 -
Exception happened during processing of request from ('127.0.0.1', 51562)
Traceback (most recent call last): File "/usr/lib/python2.7/CGIHTTPServer.py", line 247, in run_cgi os.setuid(nobody)
OverflowError: user id is greater than maximum
127.0.0.1 - - [30/Aug/2014 19:51:59] CGI script exit status 0x7f00
It is very easy to correct this error. Just change the error line (line 247 in the script CGIHTTPServer.py):
Change from this:
Then the python web server will be able to run cgi scripts. Even Perl scripts will run under this command line web server.
How to run a web server that runs PHP
You can even run php scripts using this python server, but you'll need to add the following lines at the beginning of the php file the follwing 2 lines (followed by a third empty line). Example of php file that will run under "python -m CGIHTTPServer":
1+2 = <?php echo 1+2?>
But the php script must be inside "cgi-bin" directory and must have executable permission (chmod a+x *php). I usually create a symbolic link so I don't need to move php files inside "cgi-bin" directory:
ln -s . cgi-bin