Ajax software
Free javascripts
↑
Main Page
Testing mod_rewrite
Once mod_rewrite is installed and enabled, you add the rewriting rules to the Apache configuration
file,
httpd.conf
. Apache also lets you save configuration options (including rewriting rules) on a
per-directory basis to a configuration file named
.htaccess
. All you have to do is create a file named
.htaccess
into a directory of your application, and Apache will read it automatically when accessing
that directory.
As with mod_rewrite,
.htaccess
isn’t related to PHP in any way. The
.htaccess
file is strictly an
Apache configuration file. You’ll see how it works in the exercise that follows.
Using
.htaccess
is useful in the following scenarios:
?
You don’t have access to the global configuration file,
httpd.conf
(this tends to be true in a
shared hosting account).
?
You want to have customized configuration options for a particular directory of the application.
?
You want to be able to change the configuration options without restarting Apache. You
are
required to restart Apache after modifying
httpd.conf
, and this is problematic if you have
live applications running on the web server.
All of the exercises in this book are designed to work with the
.htaccess
file. This is the method we
generally recommend for defining rewriting rules, especially in the development stage when the rules
change frequently. This way you avoid restarting Apache every time you change a rewriting rule. It is
also the only solution in a shared hosting environment, where you do not have access to
httpd.conf
and you cannot restart the server, either.
In the upcoming exercise you create a simple rewrite rule that translates
my-super-product.html
to
product.php?product_id=123
. This is the exact scenario that was presented in Figure 3-3.
The
product.php
script is designed to simulate a real product page. The script receives a query string
parameter named
product_id
, and generates a very simple output message based on the value of
this parameter. Figure 3-4 shows the sample output that you’ll get by loading
http://seophp.example
.com/product.php?product_id=123
.
To improve search engine friendliness, you want to be able to access the same page through a static URL:
http://seophp.example.com/my-super-product.html
. In order to implement this feature, you’ll
use — you guessed it! — mod_rewrite.
Older versions of Apache (1.3 and older) may also require you to add the following
line to
httpd.conf
:
AddModule mod_rewrite.c
For this reason, older mod_rewrite tutorials mention this line as obligatory, but it’s
no longer required by new versions of Apache.
49
Chapter 3: Provocative SE-Friendly URLs
c03.qxd:c03 10:39 49
Ajax software
Free javascripts
→