How To Configure Apache2 on Linux and Host Your Own Website

Intro

Virtual Hosting allows Apache to host more than one website on a single server. This is how sharing hosting works. It’s an ideal way to develop multiple web projects on the same machine.

This exercise assumes you have Apache2 running on Linux. I’m currently running Apache/2.2.17 on Ubuntu 11.04. To see what version of Apache you have installed, run apache2 -v from your terminal.

Configure Apache2 virtual hosting

Your web root folder is /var/www/, which is protected, so for development purposes, let’s move it to where you won’t need root privileges to access it, e.g., /home/matt/www/ (In this example, I’m using matt—replace this with your user directory)

In order to tell apache where we want /www/, we’ll need to edit the read-only file default in /etc/apache2/sites-available/:

  1. Open your terminal and run gksudo
  2. In the ‘Run program’ dialog box that opens, enter nautilus
  3. In the window that opens, navigate to /etc/apache2/sites-available in the file system, and edit the default file with a text editor like Gedit.
  4. Replace the 2 instances of /var/www/ with /home/matt/www/ and save.
  5. Reload the Apache configurations from your terminal by running sudo service apache2 reload
  6. http://localhost/ should now point to your new /www/ directory. Test this with a simple index.html or .php file.

Host a new site in Apache2

  1. Open your terminal and run cd /etc/apache2/.
  2. Then run cd sites-available.
  3. Create a new file called ‘mynewsite': run sudo cp default mynewsite.
  4. Edit mynewsite as root and run: sudo nano mynewsite. If you prefer another text editor such as Gedit, you can run  sudo gedit mynewsite.
  5. When mynewsite opens in your text editor, replace what’s there with:<VirtualHost *:80>
    ServerAdmin your@email.com
    ServerName greatsite.com
    Options -MultiViews
    DocumentRoot /home/matt/www/projects/mynewsite/public_html
    <Directory /home/matt/www/projects/mynewsite/public_html/ >
    Options Indexes FollowSymLinks
    AllowOverride All
    Order allow,deny
    allow from all
    </Directory>
    </VirtualHost>

    Be sure to edit the path /home/matt/www/projects/mynewsite/public_html/ both for DocumentRoot and for Directory to point to where you’d like to keep your projects.

  6. Save and close mynewsite – your new website configuration is ready.
  7. To set up the directories and subdirectories for your projects all at once, return to your home directory by running cd . Then run mkdir -p www/projects/mynewsite/public_html .
  8. Now, enable the configuration we created earlier by running: sudo a2ensite mynewsite . (a2 = Apache2 and en = enable).
  9. Tell your machine to listen for the address we chose for your site by running: sudo gedit /etc/hosts . When your text editor opens the file, add the name of the address next to localhost on the same line, like so:127.0.0.1    localhost greatsite.com 
  10. Save the file and exit your text editor.
  11. Reload the Apache configuration: sudo service apache2 reload .
  12. Load greatsite.com in your browser.

You now run Apache shared hosting!

Installing the LAMP Stack on Ubuntu 11.04 – Natty Narwhal

How to install the LAMP stack

Once you’ve installed Ubuntu, you’ll need Apache MySQL, and PHP to complete the stack. We’ll install phpmyadmin while we’re at it.

For this example I installed LAMP using Ubuntu 11.04 (Natty Narwhal), but this example  should work on many previous releases; I can’t say how far back.

  1. Open your terminal.
  2. Run sudo apt-get install apache2 mysql-server php5 phpmyadmin .
  3. Set passwords when prompted.
  4. Run sudo service apache2 restart.
  5. Go to http://localhost/ in your favorite browser. When you see Apache’s “It works” page, Apache is installed. If you get the following error:
    ... waiting apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1 for ServerName

    simply edit the httpd.conf file by

    1. running: sudo gedit /etc/apache2/httpd.conf
    2. Add the following line to the file (which will be blank be default):
      ServerName localhost
  6. Go to http://localhost/phpmyadmin. If you don’t see phpMyAdmin’s welcome page, create a symlink by running: sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf.d/phpmyadmin.conf and then reload Apache: sudo service apache2 reload . You should now see phpMyAdmin’s Welcome page.
  7. Have a sandwich.

Once LAMP is installed and running, you’ll probably want to configure Apache virtual hosting so you can begin using your new development server.

Goodbye Windows, Hello Linux.

Well I finally did it.

Sure, it’s a dual-boot, but I’m committed to using Linux only on my main laptop.

Once I get Photoshop working through VirtualBox—which might require a bit more RAM—I’ll kiss the windows partition goodbye. I don’t have time to shift to GIMP right now, so I’ll be keeping Photoshop in my toolkit for now.

The recent version of Ubuntu, 11.04 (Natty Narwhal) loads the Unity user interface instead of GNOME Shell as default, which was a bit of a turn off for me. Ubuntu 10,10 (Maverick Meerkat) using GNOME was a nice introduction to Linux for me last year; I find GNOME to be much more intuitive.

Thankfully, reverting to the Gnome environment in Natty is as simple as logging out and selecting it as your GUI.

Aside from the Photoshop inconvenience, it looks like I’ll also need to load Magic Jack through VirtualBox as well.

Hey Adobe: 2011 called, they want their Photoshop back.

Goodbye Gates, hello Torvalds.

Django Views and URLconfs – Your First Django page

This mini tutorial explains how to serve a simple web page through Django that display’s a traditional ‘Hello world’ message.

The examples on this page assume that you have completed the Django installation, and have started a new Django project in a directory named /mysite/.

Key concepts

In Django, the contents of the page are produced by view a function, which you place in a file you create, conventionally named views.py. The URL of the page itself is specified in a URLconf,, which you specify in urls.py.

Sample view

To output a simple Hello world! message, add this to your new views.py:

from django.http import HttpResponsedef hello(request):     return HttpResponse("Hello world")

Translation:

  • Import the HttpResponse class, from django/http/ (or, the django.http module)
  • Define a function called hello. This is our view function.
  • Return an HttpResponse object that’s been instantiated with the text Hello world.

In order for a Python function to be a Django view, it must do two things:

  1. Takes an HttpRequest as its first parameter.
  2. Return an instance of HttpResponse.

Each view function takes at least one parameter, called request by convention.

Sample URLconf

Default URLconf:

If we ignore the code that’s commented out of the urls.py file (the one that was created when you first created your Django testProject folder), we’re left simply with:

from django.conf.urls.defaults import *urlpatterns = patterns('',)

Translation:

  • Import all objects from the django/conf/urls/defaults/ (the django.conf.urls.defaults module). This includes the proceeding function, patterns.
  • Calls the function patterns and save the result into a variable called urlpatterns.

Edit the URLconf:

from django.conf.urls.defaults import *from mysite.views import hellourlpatterns = patterns('',    ('^hello/$', hello),)

Translation:

  • Import the hello view from the mysite.views.py module.
  • Any request to the URL /hello/ should be handled by the hello view function.

Things to remember

  • mysite/views.py must be on your Python path.
  • If you want to load this page from Apache as http://127.0.0.1/hello instead of as http://127.0.0.1:8000/hello from Django’s development server, make sure that the following is in Apache’s configuration file (httpd.conf):

    <Directory C:/mysite>
    Order deny,allow
    Allow from all </Directory>
  • The URLpattern ('^hello/$', hello), is a Python tuple in which the first element is a regular expression, and the second is the view function to use for that pattern.

Test your first Django page

Either run the command python manage.py runserver to view your /hello/ page in Django’s development server at http://127.0.0.1:8000/hello, or view it with your Apache web server at http://127.0.0.1/hello .

The page you see from this example is static; the content doesn’t change from user input, nor does it involve any database. Move on to a simple example of a dynamic Django page—as well as to an introduction to dynamic URLs—in Chapter 3 of DjangoBook: Views and URLconfs.

10 Improvements Posterous Needs To Make

Note: This post is no longer relevant, as Posterous was shut down April 30, 2013, after much of the team was acquired by Twitter on March 12, 2012.

I’m quickly realizing that while Posterous is said to be a fast and easy solution for making blog posts from your email when you’re on the go, it’s lacking some fundamental features I’d expect from any serious blogging platform.

This list will grow (hopefully not much more) as I make new preposterous discoveries.

  1. Give us our alt attributes: Alt attribute text is non-existant and can’t be added. Accessibility issue.
  2. Let us control our image file names: Image file names are changed to horrendously long random strings when you upload using the media uploader, and they can’t be modified. Accessibility issue.
  3. Let publishers decide what (and what not) to syndicate: All posts are given canonical attributes, and you can’t undo this “feature”. Ethics issue.
  4. Let us preview our posts: Posts can’t be previewed—only updated—which automatically takes you out of the editor and displays the published page in its place. Usability issue.
  5. Let us save posts quickly: Posts can’t be saved without being updated, which takes you out of the editor (see previous complaint). Usability issue.
  6. Watch our back. Just a bit: There is no autosave feature. Usability issue.
  7. Let us edit our comments: Comments can’t be edited, only deleted and re-posted in the case of typos or other errors. Usability issue.
  8. Let us reply to specific comments: Admins can’t reply to specific user comments. Usability issue.
  9. Let us name anchors: Posterous automatically strips id or name attributes from most HTML elements, which prevents you from linking to specifics section of your pages. Usability issue. The workaround: Add an empty anchor with a name attribute just before the section you want to name, e.g., <a name="anchor_name"></a>. Thanks to Luke Sampson for this useful little hack.
  10. Fix your HTML rendering issues: Just one example of straightforward HTML that doesn’t render properly in Posterous, although it renders properly in their “rich text editor”. em>Usability, accessibility issue. I’ve included a screencast due to the inability to properly markup the code in Posterous.

    Click on the icon next to the Screenr Logo (bottom right of the player) to see the video at a decent size
    :Since moving this blog from Posterous to WordPress, the Screenr widget is no longer embedded, since WordPress.com doesn;t allow iframes. Here’s the link to the video instead: http://www.screenr.com/qywIn item 9 of this list, I left the last &gt; (>) symbol outside of the <code> element, immediately after the closing </code> tag. Another ugly hack, but I’m getting used to the fact that to makes things work in posterous, you often have to get ugly.

Installing Python and Django on WampServer

Here’s a step by step guide to installing Python and Django on top of the WAMP stack. I’ve used Windows XP in this example, but there shouldn’t be much difference with Windows 2000, NT, 7, Vista, etc.

If you have any problems (or even if you don’t) don’t hesitate to leave your comments so others might benefit from your experience, good or bad.

1. Install Wampserver

The latest release of WAMP is WampServer 2.1a [24/12/10], and includes:

  • Apache 2.2.17
  • Php 5.3.3
  • Mysql 5.1.53 (version 64 bits)
  • Mysql 5.5.8 (version 32 bits)
  • PhpMyadmin 3.2.0.1
  • SQLBuddy 1.3.2

However, for this example I’m using the previous version of WampServer, 2.0-i [07/11/2009]. It’s unlikely this will cause you any problems. WampServer 2.0-i looks like this:

  • Apache 2.2.11
  • Php 5.3.0
  • Mysql 5.1.36
  • PhpMyadmin 3.2.0.1

Once WAMP is installed and running properly, give yourself a pat on the back on move on to step number 2.

2. Install Python

  1. Download a current production version of Python for Windows. At the time of this writing, Django supports 2.x versions only.
  2. Install your file (ex: python-2.7.1.msi) to your desired location. For this example, I’ll choose C:Python27
  3. Test Python’s interactive interpreterMake sure that your command window recognizes ‘python’ as a command to start the interpreter:
    1. Open your command window.
    2. Type the command python and hit enter.
    3. If things are working as they should, you should see something like:

      Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32
      Type “help”, “copyright”, “credits” or “license” for more information.
      >>>

    …and you can proceed to install Django.

    If instead you get an error such as:

    ‘python’ is not recognized as an internal or external command, operable program or batch file.

    then you’ll need to add Python’s installation directory path to your command window as an environmental variable. Here’s how it’s done in Windows XP:

    1. Go to the properties window of ‘My Computer’, and then to the ‘Advanced’ tab
    2. Click on ‘Environmental variables’ at the bottom of the ‘advanced’ tab.
    3. If there’s no PATH variable present on the left had side, click ‘new’ and add Path with a corresponding value on the right (in this case, C:Python27). You can choose to do this for either your Windows user account or system (all users). If a PATH variable is present, select it, click ‘edit’ and simply add the C:Python27 path as a variable directly after them, preceded by a semicolon as in fig 1.

      Add new environmental variable

      Fig. 1 – Add new environmental variable

    4. Click ‘ok’, and ‘ok’ again to close the ‘system properties’ window.
    5. Open a new command window, and type python and hit enter again. You should now see the message I mentioned earlier; something similar to:

      Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32
      Type “help”, “copyright”, “credits” or “license” for more information.
      >>>

      In the unlikely event that you still don’t see this message, it’s time to hit up Google and/or leave a comment at the end of this post.

3. Install the Python WSGI (Web Server Gateway Interface) adapter module for Apache

Mod_wsgi (pronounced as ‘wiz-gee’) is an Apache HTTP Server module that provides a WSGI compliant interface for hosting Python based web applications under Apache.

  1. Download mod_wsgi for your version of Apache and Python. For this example, I used mod_wsgi-win32-ap22py27-3.3.so since I’m running Apache 2.2 and Python 2.7.
  2. Rename the downloaded file to mod_wsgi.so and move it to the modules/ folder of your Apache installation in WampServer.
  3. Add the following to your Apache configuration file (httpd.conf) for Apache to recognize python applications:LoadModule wsgi_module modules/mod_wsgi.so
    and, to grant Apache rights to serve scripts from a directory we’ll use for our Django projects:
    <Directory C:/projects/testProject>
    Order deny,allow
    Allow from all
    </Directory>

    Restart Apache
  4. Once you’ve got mod_wsgi installed and activated, add the following to your  httpd.conf file:

    WSGIScriptAlias / "c:/projects/testProject/django.wsgi"

    and then, create a file named django.wsgi. To it, add the following:
    import os, sys
    sys.path.append('c:/projects/') os.environ['DJANGO_SETTINGS_MODULE'] = 'testProject.settings'
    import django.core.handlers.wsgi
    application = django.core.handlers.wsgi.WSGIHandler()
    Place django.wsgi in c://wamp/www/projects/testProject.

4. Install Django

  1. Download Django, and unpack the tarball to any folder. Let’s use C:Documents and SettingsMattMy Documents. Once the tarball is unpacked, you’ll have a folder such as C:Documents and SettingsMattMy DocumentsDjango-1.3 which contain Django’s installation files. Copy this path from the address bar.
  2. Open a command window and change directory to Django’s installation files folder. In this case you would type cd C:Documents and SettingsMattMy DocumentsDjango-1.3.
  3. Verify that you see the contents of the folder with the dir command.
  4. Run the Django setup file by running
    python setup.py install
  5. Once the installation is complete, type python and hit enter to get the Python prompt, and then type import django. Hit enter.
  6. If nothing happens at this point, i.e., no errors appear, Django is successfully installed.
  7. Let’s test it.
    1. Create a folder for your various Django projects; say c:/projects/ for example. (Unlike with what you might be used to with PHP, your Python code and Django project files should be outside your Web server’s document root for added security).
    2. Open your command window and change directories to your c:/projects/ folder.
    3. Run the command

      django-admin.py startproject testProject

      to create a subfolder called testProject/ that will automatically contain 4 project files. If you get a command not found type error, it means you’ll need to add the path to django-admin.py as an environmental variable to window’s system path, similar to what you might have done when installing Python:

      1. Go to the properties window of ‘My Computer’, and then to the ‘Advanced’ tab.
      2. Click on ‘Environmental variables’ at the bottom of the ‘advanced’ tab.
      3. If there’s no PATH variable present on the left hand side, click ‘new’ and add Path with a corresponding value on the right (in this case, C:Python27Scripts). You can choose to do this for either your Windows user account or system (all users). If a PATH variable is present, select it, click ‘edit’ and simply add the C:Python27Scripts path as a variable directly after them, and preceded by a semicolon as in fig 2.
        Edit environmental variable

        Fig. 2 – Edit environmental variable

    4. When the command django-admin.py startproject testProject completes with no errors, you’ll have 4 project files. To verify that this this worked, cd to your c:projects/testProject/ directory and run the command python manage.py runserver . You’ll see the following output on the command line:
      Validating models...0 errors found.Django version 1.0, using settings 'mysite.settings'Development server is running at http://127.0.0.1:8000/Quit the server with CONTROL-C.

      This confirms that you’ve started the Django development server, a lightweight Web server written in Python.
      When Django’s development server is running, visit http://127.0.0.1:8000/ to see your first Django-powered page. This server is available to you should you prefer to use it over Apache. However, now that you’ve installed mod_wsgi, Django will run from Apache without having to start the development server at all.
      Visiting http://127.0.0.1 (no port 8000 specification) will confirm that django is now running on Apache.

      Since this guide focuses on using Django with WampServer, we’ll need to install the Python MySQL library next.

5. Install the Python MySQL library

The MySQL-Python package allows Python to interface with WampServer’s MySQL database.

  1. Download the most recent version of MySQL-Python for Windows.
  2. Run the installer.
  3. Send thanks to Ioannis Lalopoulos, his MySQL-Python module just saved you from spending a helluva lot of time trying to compile the MySQLdb on Windows.

Django’s MVC framework

Django is a Model–view–controller (MVC) framework, or software architecture. This type of architectural pattern isolates domain logic (the application logic for the user), user interface (input and presentation), and testing and maintenance of each (separation of concerns).

Standard MVC frameworks

Typically, an MVC framework looks like this:

  • Model: Database and business logic (domain logic).
  • View: The view manages the display of information, or look and feel.
  • Controller: The controller interprets the mouse and keyboard inputs from the user, and maps one to the other.

Django’s MVC framework

Django is more of a Model-Template-View framework due to its templating feature, where:

  • Model: Database and business logic (domain logic).
  • Template:  The separation of content from presentation.
  • View: In Django, the view describes which data is presented, not how you see it. In typical MVC frameworks, the view delegates to a template, which describes how the data is presented. According to Django’s FAQ page, …a “view” is the Python callback function for a particular URL, because that callback function describes which data is presented.

Django’s controller is the framework itself: the machinery that sends a request to the appropriate view, according to the Django URL configuration.