How can I get started with `mod_rewrite` on my Linode running Apache?
I'm trying to enable
mod_rewrite for Apache, but it doesn't seem to be taking. What might my configuration need to look like?
To begin, we have to enable
mod_rewrite. After installing Apache by running
sudo apt-get install apache2,
mod_rewrite can be enabled for Apache on Debian and Ubuntu by running the following command:
sudo a2enmod rewrite
Once you've enabled
mod_rewrite, we have to restart Apache to fetch the new configuration. The best way to do this would be to use
apachectl, which will helpfully display any errors that might occur on reboot.
sudo apachectl graceful
apachectl to please reboot Apache in a nice way, without forcing all child processes to quit immediately.
In our example, we'll be making settings that just modify what requests to
example.com/foo look for on the backend. In this case, we'll be having those requests return the contents of the file
bar. For our purposes, all the files for
example.com will be stored in the following directory:
And within that directory, we'll have a file titled
bar, which just contains the following line:
bar, we just need to modify the Virtual Host file of our website to setup our rewrite rules. This will be done by modifying the
.conf file for our site. In this case, we'll be modifying the file located at
example.com.conf, add the following block:
<Directory "/var/www/example.com/html"> RewriteEngine On RewriteRule "^foo$" "bar" </Directory>
Let's review what's going on in this block:
Directorydirective lets Apache know that the directives enclosed in that block apply specifically to the directory we specify in the opening tag. In this case, our content is in
/var/www/example.com/html, so we specify that directory.
mod_rewritefor the context we're currently working in.
RewriteRuletells Apache how it should be rewriting requests.
There's a bit going on in the
RewriteRule directive, so let's break that down as well.
^at the beginning of
foonotes that this is the beginning of the pattern to match requests against
$at the end denotes that the pattern is finished. Both of these markers reflect logic following regular expression syntax.
- Finally, the last string just says to replace anything that matches with that pattern (essentially, any requests for
example.com/foo) serve the contents of
Now that we've got that taken care of, we just need to restart Apache again.
sudo apachectl graceful
If there weren't any errors, when we send a request to
example.com/foo, we should get the contents of
This is just a very simple example of what can be accomplished with
mod_rewrite. For more tips and tricks, check out the official documentation, and definitely be sure to check out our handy docs page on the subject: Rewrite URLs with mod_rewrite and Apache.