Go Premium for a chance to win a PS4. Enter to Win

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 406
  • Last Modified:

mod_rewrite questions

I wanted to do the two following things with mod_rewrite (or any other mod if possible):

1) Prevent hotlinking
2) Resolve relative URL's (such as /articles/9/ would actually read articles.php?ID=9)

Thanks in advance.
1 Solution
drakkarnoirAuthor Commented:
So nobody knows how to do this?

the second point could be done like this

RewriteEngine On

RewriteRule ^(.+)/$ /$1   ## remove trailing slash
RewriteRule ^/articles/(.*)$    /article.php?id=$1  [R,L]    ## redirect to the URL and stop the processing

Hotlinking prevention, see: http://www.htmlite.com/HTA013.php

Dynamic - Static URL's:

First of all take a look at these links, they show the basics of mod rewriting very well:


The basic steps are this:

1) Create a .htaccess file.

2) Add this line:

RewriteEngine on

This effectively initiates the Apache module used for the mod rewriting.

3) Now for the rewrite rules, the syntax is as follows:

RewriteRule The_Pattern The_Replacement

The pattern and the replacement are often based on regular expressions so if you have no previous knowledge of regex now would be a great time to brush up on your knowledge.

A very brief overview of meta characters you will more likely need:

^  beginning of item/line
$  end of item/line
\  used to escape certain characters
.  matches any character (but not new line)
[]  used to define accepted character classes
|  "or" - or an alterantive
()  grouped pattern
*  0 or more
+  1 or more
{}  min/max quantity

Here is a few examples of how you can use mod rewriting:

RewriteRule /articles/([0-9]+) /articles.php?id=$1

/articles/2   >>>   /articles?id=2

RewriteRule /category/([a-z]+)/([0-9]+) /category.php?action=$1&cat=$2

/category/show/3   >>>   /category.php?action=show&cat=3

RewriteRule ^cat_([0-9]+)_([0-9]+).html$ category.php?cat=$1&page=$2

cat_1_3.html   >>>   category.php?cat=1&page=3

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now