Setting up mod_rewrite on ubuntu example. Only the useful.

mod_rewrite is a way to change one url to another. It is very useful for making dynamic php sites better for search engine optimization (SEO).

Obviously you’re going to need apache installed. I’m using Apache 2.0 with php5. This is how I did it.

I had hoped that it was already installed and I could just start writing regular expressions in an htaccess file and have everything work. So I went to check if it was installed by calling the phpinfo function. I created a file called asdf.php which contained:

I then did a search for rewrite in my browser. No go. So it’s either not installed or not enabled.
I checked the /etc/apache2 directory for any files that look like mod_rewrite.
I found rewrite.load in the mods-available directory. There is also a mods-enabled directory so I copied rewrite.load to mods-enabled with this command.


cody@taylor:/etc/apache2$: sudo cp rewrite.load ../mods-enabled/rewrite.load

I thought this may do it so I restarted apache2 with this command:


cody@taylor:/etc/apache2$: /etc/init.d/apache2 restart

I created two text files to test whether it was working:


filename: test.html
This is a HTML File

filename: test.php
This is a PHP File

I then created a .htaccess file in my web root directory which contained this text:


RewriteEngine on
RewriteRule ^/?test\.html$ test.php

I went to http://localhost/test.html hoping to see that it’s a php file. Didn’t work obviously.
I checked the sites-enabled directory and opened 000-default in vim.

It contained :

ServerAdmin webmaster@localhost
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all

ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
ErrorLog /var/log/apache2/error.log

# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn

CustomLog /var/log/apache2/access.log combined

Alias /doc/ “/usr/share/doc/”
Options Indexes MultiViews FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
Allow from 127.0.0.0/255.0.0.0 ::1/128

AllowOverride is what I was looking for so I change AllowOverride to all and restart apache again.
This time when i check http://localhost/test.html I get that it is a php file which is good.

I noticed I was getting this error when I restarted apache:


cody@taylor:/etc/apache2$: sudo /etc/init.d/apache2 restart
* Restarting web server apache2
apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1 for ServerName
... waiting apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1 for ServerName

I fixed this by adding this line to the apache2.conf file:


ServerName "codytaylor.org"

A restart fixed it all up.

-Cody Taylor

Share

Comments are closed.