6.4. Using MySQL with Apache

By now, you've created a security zone or two using Apache and basic authentication, and for most situations, that might be all you need. You may find, however, that basic authentication with Apache, while simple, is a little too limited in the amount of control and customization you can incorporate. For many such situations, you can actually use a combination of Apache basic authentication and the power of relational databases via MySQL. For such a purpose, the mod_auth_mysql Apache module exists.

Like standard Apache basic authentication, mod_auth_mysql can control access per-directory, and can be configured inside both .htaccess files and a <Directory> section inside httpd.conf. Unlike standard Apache basic authentication, all user credentials are stored in a database, instead of in flat files.

6.4.1. Setting Up the Database

Installing and configuring mod_auth_mysql involves a few steps, the first of which is to create the necessary database structures to hold the user data. Start by loading up your favorite MySQL client, and creating the database. For example:

CREATE DATABASE apacheauth;

Next, create a user that will be used by Apache to access the credentials:

GRANT SELECT ON apacheauth.* TO apache@localhost IDENTIFIED BY 'apachepass';

Now that the database user is created, it's time to add a table to hold the login information. For now start out with a simple table that just holds the username and password:

USE apacheauth; CREATE TABLE user_info ...

Get Professional LAMP: Linux®, Apache, MySQL®, and PHP5 Web Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.