Search code examples
cherrypy

cherrypy serve index.html at root (but not other files)


Using cherrypy, I am able to serve a static index.html file by using the below configuration information:

location = os.path.dirname(os.path.realpath(__file__))
conf = {
     '/': {
         'tools.staticdir.on': True,
         'tools.staticdir.dir': '',
         'tools.staticdir.root': location,
         'tools.staticdir.index': 'index.html'
     }
}
cherrypy.tree.mount(Root(), '/', conf)
cherrypy.engine.start()
cherrypy.engine.block()

However, in doing so it looks like I'm also exposing all of my files in the web root directory. For example, people can also download server.py (which contains my cherrypy code).

Is there a way to get around this? I know that some people will attempt to access my site by doing http://www.example.com/index.html and I don't want them to 404 each time, since cherrypy will only allow them to go to http://www.example.com or http://www.example.com/index this seems like a problem to me.


Solution

  • An urgent thing is to separate the code of static content. Create, for example, a 'static' directory, as shown.

    And as for index.html, whether it should be an alias for '/', you can create methods, replacing their names on the occurrences of '.' . by '_', as explained here: cherrypy: respond to url that includes a dot?

    An example:

    #!/usr/bin/env python
    
    import os.path
    import cherrypy
    
    class Root:
        @cherrypy.expose
        def index(self):
            return "bla"
    
        index_shtml = index_html = index_htm = index_php = index
    
    location = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'static')
    
    conf = {
         '/': {
             'tools.staticdir.on': True,
             'tools.staticdir.dir': '',
             'tools.staticdir.root': location,
         }
    }
    
    cherrypy.tree.mount(Root(), '/', conf)
    
    cherrypy.engine.start()
    cherrypy.engine.block()