Technical notes‎ > ‎

Create a simple site with Python CGI on Apache 2 - Fedora 18 - Fedora 19 - Fedora 24

posted May 9, 2014, 9:50 AM by Le Tuan Anh   [ updated May 15, 2017, 8:53 PM ]
Source code repository: https://github.com/letuananh/pcdemo
  1. su to become root
  2. Create the following directory structure
    • /var/www/mysite
      • cgi-bin
        • index.py
      • html
        • index.html
  3. Sample content for index.py
    #!/usr/bin/python

    print("Content-type: text/html\n")
    print("""
         <html>
         <body>
              Hello Python CGI <br/><a href='../'>Home</a>
         </body>
         </html>
         """)

  4. Sample content for index.html
    <html>
      <body>
        Home <br/>
        <a href='cgi-bin/index.py'>CGI</a>
      </body>
    </html>
  5. If you use SQLite, create a sample database file.
  6. edit /etc/httpd/conf/httpd.conf, add the following code to the end of the file
    ScriptAlias /mysite/cgi-bin/ /var/www/mysite/cgi-bin/
    Alias /mysite/ /var/www/mysite/html/

    <Directory "/var/www/mysite/cgi-bin/">
        AddHandler cgi-script .py .cgi
        AllowOverride None
        Options +Indexes +ExecCGI
        Order allow,deny
        Allow from all
    </Directory>

    <Directory "/var/www/mysite/">
        AllowOverride None
        # Allow open access:
        Require all granted
    </Directory>
  7. Run the following code in the terminal
    chcon -h -t httpd_sys_content_t /var/www/mysite/cgi-bin/
    # You need this line if you want to write to a database file
    chcon -h -t httpd_sys_content_rw_t /var/www/mysite/cgi-bin/database.db
    chcon -h -t httpd_sys_script_exec_t /var/www/mysite/cgi-bin/*.py
    chgrp apache /var/www/mysite/html -R

    chmod uo+r /var/www/mysite/html -R
    chmod uo+x /var/www/mysite/cgi-bin -R
  8. Now try to start server by typing
     service httpd start
  9. Go to your website from your browser at: http://localhost/mysite/

Read more


- To be updated -
Comments