«

»

Apr
18

Apache, mod_rewrite, and you

mod_rewrite is an awesome module for apache that allows you to rewrite urls. Describes itself right? Like all other apache modules, simply loading the module won’t do jack. You have to configure your apache server, telling it how you want to use mod_rewrite and where you want to use it.

Install mod_rewrite
If you already have apache installed, chances are that you already have the mod_rewrite module. If not, install it.

Debain only

egeste:/etc/apache2# a2enmod rewrite

Load the module in your apache config
Like all other daemons, apache relies on configuration files to tell it how to behave. Common configuration changes for apache would be to load/unload modules, change error or access log locations, etc. If your version apache loads modules in the configuration file, uncomment or add the following line to your config.

LoadModule /path/to/mod_rewrite.so

If your version of apache loads modules from the mods-enabled folder, create a symbolic link to the mod_rewrite config file in mods-enabled. This is what it would look like for me.

egeste:~# cd /etc/apache2/mods-enabled
egeste:/etc/apache2/mods-enabled# ln -s ../mods-available/rewrite.load

Enable .htaccess override in your web application root directory
Enabling .htaccess to override some settings in the root dir of your application allows you to change the way apache will behave in that directory without the need to restart the apache daemon. I like to add this setting to my vhost config. This is what mine looks like (some info redacted).

egeste:/etc/apache2# cat sites-available/egeste.net.conf
<VirtualHost *:80>
 ServerAdmin webmaster@localhost
 DocumentRoot /path/to/site/root
 ServerName www.egeste.net
 ServerAlias egeste.net
</VirtualHost>
<Directory /path/to/site/root>
 Options FollowSymLinks
 AllowOverride All
 Order deny,allow
 Allow from all
</Directory>

At this point go ahead and give your apache server a restart.

egeste:/etc/apache2# /etc/init.d/apache2 restart

Cool, if all went well, you should have mod_rewrite installed, loaded and configured to allow .htaccess overrides in your site root. The only steps that remain are to define a ruleset in .htaccess and write your web application to handle the requests. I won’t go into detail on mod-rewrite rules and regex, but here’s my wordpress .htaccess file.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

Happy coding =)

-Egeste

Permanent link to this article: http://egeste.net/blog/2010/04/18/apache-mod_rewrite-and-you/

Leave a Reply

Your email address will not be published.