Friday, 23 May 2014

Deploy Django with apache2 in Virtualenvs

Virtual Hosts

Apache2 has the concept of sites, which are separate configuration files that Apache2 will read. These are available in /etc/apache2/sites-available. By default, there is one site available called 000-default. This is what you will see when you browse to http://localhost or You can have many different site configurations available, and activate only those that you need.
As an example, we want the default site to be /home/user/public_html/. To do this, we must create a new site and then enable it in Apache2.
To create a new site:
  • Copy the default website as a starting point. sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/mysite.conf 
  • Edit the new configuration file in a text editor "sudo nano" on the command line or "gksudo gedit", for example: gksudo gedit /etc/apache2/sites-available/mysite.conf
  • Change the DocumentRoot to point to the new location. For example, /home/user/public_html/
  • Change the Directory directive, replace <Directory /var/www/> to <Directory /home/user/public_html/>
  • You can also set separate logs for each site. To do this, change the ErrorLog and CustomLog directives. This is optional, but handy if you have many sites
  • Save the file
Now, we must deactivate the old site, and activate our new one. Ubuntu provides two small utilities that take care of this: a2ensite (apache2enable site) and a2dissite (apache2disable site). 

$ sudo a2dissite 000-default && sudo a2ensite mysite
$ sudo /etc/init.d/apache2 restart
If you have not created /home/user/public_html/, you will receive an warning message
To test the new site, create a file in /home/user/public_html/

$ echo '<b>Hello! It is working!</b>' > /home/user/public_html/index.html
Finally, browse to http://localhost/ 
$ vim /etc/apache2/sites-available/mysite
Inside mysite 

        WSGIPythonPath /home/user/site:/home/user/.virtualenvs/test/lib/python2.7/site-packages
        WSGIPythonHome /home/user/.virtualenvs/test
<VirtualHost *:80>

        <Directory /home/user/.virtualenvs/test/lib/python2.7/site-packages>
        Options Indexes
        Order deny,allow
        Allow from all

        WSGIScriptAlias /site /home/user/site/site/
        <Directory /home/user/site/site>
        Order deny,allow
        Allow from all

        Alias /static/ /home/user/site/static/
        <Location "/static/">
            Options -Indexes
        </Location > 

No comments:

Post a Comment