Can my server module (with http.server.HTTPServer
) use something like the RewriteRule
for redirect all traffic into a single cgi script? I'd like to be able to do what's shown here in this other question, but for my python server.
Can it be done using something like .htaccess
, or is there another way?
Also, can this be done even for a simple localhost development server?
I am serving files for development via, for example, http://localhost:8000/html/index.html, and I would like to hide the /html subfolder from the URL even in development.
How can that be achieved?
You can use a custom script to initialize your server and define your Routes in it, such as suggested in this article:
Python 2:
Then run your script:
Python 3:
In Python 3 the
BaseHTTPServer
and theSimpleHTTPServer
modules have been merged into thehttp.server
module. So you will have to modify the above script as follows:Change the
to
(if you do this then the calls should be modified to
http.server.SimpleHTTPRequest
etc.)or
(with this option calls remain the same as the original script)
then run the server script:
python server.py
IN YOUR CASE:
You should modify the
ROUTES
variable to suite your needs.For example, you want to hide the
/html
folder from your url:Now if you hit:
http://localhost:8000/index.html
you will be in your home page.Note:
This script by default will serve the contained files in the folder that is in when executed to the domain url (ex. I have
server.py
on the Documents folder, then when I run it, http://localhost:8000 url will server my Documents folder).You can change this behavior by the Routes (see the 'default' match comment on the code) or by placing the script in your projects root folder and start it from there.