How to configure python with apache in ubuntu?

Common Gateway Interface(CGI) helps you run python application in apache webserver in ubuntu. Follow the steps which help you to configure python with apache webserver.

Step 1:

[code] sudo mkdir /var/www/python [/code]

Step 2:

[code] sudo vim /etc/apache2/sites-available/default [/code]

Step 3:

Add the following lines in “default” file and save the file.

[code]
ScriptAlias /python/ /var/www/python/
<Directory "/var/www/python">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all

[/code]

Step 4:

Restart the apache server to reflect the changes you made in apache configuration file.

[code] sudo /etc/init.d/apache2 restart [/code]

Step 5:

Now can run your python file under this directory “/var/www/python”

[code] sudo vim /var/www/python/hello.py [/code]

Add these lines in your ‘hello.py’ file to test python is configured correctly

[code]
#!/usr/bin/python
print "Content-type:text/html\r\n\r\n"
print ‘<html>’
print ‘<head>’
print ‘<title>Hello Word – First CGI Program</title>’
print ‘</head>’
print ‘<body>’
print ‘<h2>Hello Word! This is my first CGI program</h2>’
print ‘</body>’
print ‘</html>’
[/code]

Step 6:

Before running your python file under this directory, make sure you have chage mode of file using chmod 755.

[code] sudo chmod 755 hello.py [/code]

Step 7:

Now you can request the page url in browser to load the python

[code] http://localhost/python/hello.py [/code]

Permanent link to this article: https://blog.openshell.in/2013/03/how-to-configure-python-with-apache-in-ubuntu/

Leave a Reply

Your email address will not be published.