RewriteRule
takes a regular expression which can be as complicated as you want it followed by the real URL that will load your file. You put parenthesis around the parts you want to capture in the regex and can reference those with $1
for first group, $2
for second group and so on in the URL part. For example:
RewriteRule ^(\w+)/(\d+)/(.*)$ index.php?file=$1&id=$2&words=$3
This would match 3 groups:
- letters/numbers up to the first slash
- some numbers up to the second slash
- anything after that including additional slashes
And those can be referenced by $1
, $2
, $3
as seen in the second part with index.php.
The only issue with this though is that if you are missing any one part, the pattern in the rule won't match. So you either need to have a separate rule for each variant:
RewriteRule ^(\w+)/(\d+)/(.*)$ index.php?file=$1&id=$2&words=$3
RewriteRule ^(\w+)/(\d+)$ index.php?file=$1&id=$2
RewriteRule ^(\w+)$ index.php?file=$1
RewriteRule ^.*$ index.php
Or you can do what is usually called bootstrapping
which is where you use a single RewriteRule
to redirect everything to a single php file like so:
RewriteRule ^(.*)$ index.php
And then you can just use php to determine what the different parts are. Inside php there is a built in server variable $_SERVER['REQUEST_URI']
that will give you the URI
part of the url which is everything after the domain and first slash including any query string parameters. This is based on the URL that the user requested and not the one rewritten by apache. You can explode('/', $_SERVER['REQUEST_URI'])
to get the individual parts and do whatever you want with them.