How to make a simple rewrite rule for an Apache webserver using .htaccess:
- Make a file in the web directory to be affected named ".htaccess" (with the leading period).
- Put the following text into it:
RewriteEngine on
- Below this, put a line in the following format:
RewriteRule original new [options]
- for example, to make any request for a file name ending with ".html" go instead to ".php" instead, the following is a good one:
RewriteRule ^(.*)\.html$ $1.php [NC]
The particulars of the regular expression syntax and all of the options are beyond the scope of this document.
As always, end your .htaccess file with an empty line.
Pretty URLs
mod_rewrite is perhaps best known for the functionality to keep the urls of your site clean, and to help obscure the underlying technology.
Here is an example .htaccess file to prettify some sample urls
RewriteEngine on RewriteRule ^foo foo.html RewriteRule ^search/widgets search.php?q=widgets RewriteRule .* index.php?page=$1 [L]
Caveats
- On Sonic.net hosting, the mod_rewrite module may not show up in a phpinfo() readout. It is nonetheless installed and active.
- Rewrites are different than redirects - the url in the address bar remains the same, even if the content is at a different location.
For redirects, view our article on .htaccess
0 comments
Please sign in to leave a comment.