Apache htaccess with MySQL

From Linuxhelp Wiki

Author:x2xtreme
Created On:June 5th, 2000
Updated On:Unknown

First off, you will need to have Apache and MySQL installed. You can download Apache at http://www.apache.org/dist/. For information on installing Apache, see Joey's Apache Guide. Once Apache is set up, you will need MySQL installed and running. You can download the MySQL source from http://www.mysql.com and for information on installing and setting up MySQL, you can read DJG's MySQL Guide.

After that, you need to retrieve the source for the mod_auth_mysql source.

Place the source into your apache tree in the libexec directory. Mine is located at /usr/local/apache/libexec/

Next, you need to change directories to your apache bin, I would do this

cd /usr/local/apache/bin/

Then compile everything:

./apxs -c -L/usr/local/lib/mysql/libmysqlclient.so.6 -lm ../libexec/mod_auth_mysql.c

That should compile everything nicely. Now you will need to edit your httpd.conf file:

pico ../conf/httpd.conf

You should place a couple of lines into it. The first line should go at the end of your LoadModule section and look like this:

LoadModule mysql_auth_module  libexec/mod_auth_mysql.so

Then next line should go at the end of your AddModule section and it should look like so:

AddModule mod_auth_mysql.c

Now, save this and see if it works by restarting apache:

./apachectl restart

Everything should work out fine and you will be ready to create your table structure.

Next you need to set up your Database and Table for Authentication. There are various ways to go about this, I will give you the SQL query that will do this for you. You can use this query in the MySQl admin tool, or in phpMyAdmin, which I do:

CREATE TABLE user_auth (
	user_name CHAR(30) NOT NULL,
	user_passwd CHAR(20) NOT NULL,
	user_group CHAR(10),
	PRIMARY KEY (user_name)
	);

That should leave you with a nice little table that you can add things to in the future if need be. There are only two things left to do now, populate that table with data, and edit the httpd.conf one more time. Edit the httpd.conf again, and put this in a directory configthat you need for the directory you would like password protected.

‹Directory /path/to/directory>
    Options Indexes FollowSymLinks
    AllowOverride AuthConfig
    order allow,deny
    allow from all
‹/Directory>

Now you will need to create your .htaccess file with these special parameters:

AuthName			"Authorization Required"
AuthType			Basic
AuthGroupFile			/dev/null
AuthMySQLCryptedPasswords	Off
AuthMySQLHost			localhost
AuthMySQLDB			
AuthMySQLUserTable		user_auth
AuthMySQLUser			
AuthMySQLPassword		
AuthMySQLNameField		user_name
AuthMySQLPasswordField		user_passwd
AuthMySQLAuthoritative		On
require valid-user