views:

91

answers:

3

Using LAMP, is it possible to write rewrite rules to redirect URLs like the following?

http://example.com/topic/142 -> http://example.com/static/14/142.html

--Edit--

The rule is to get ID's first 2 numbers as folder name, then ID.html.

A: 

Is it possible, yes, surely.

RewriteRule /topic/(.+) /static/14/$1.html

However, this will give you the /14/ part every single time. As long as you don't have a hint were this part is encoded in your original URL, there is no way to change this.

Martin Hohenberg
rule added , seems impossible to archive this by rewrite
lzyy
+3  A: 

Try this rule:

RewriteEngine on
RewriteRule ^topic/(([0-9]{2})[0-9]*)$ static/$2/$1.html
Gumbo
That will fails as soon as the ID exceeds 999...
Martin Hohenberg
@Martin Hohenberg: It will fail for numbers smaller than 10. And the folder name is identical to the ID for the numbers 10 to 99. But there is no upper limit.
Gumbo
hm, seems the OP was edited sometime after I wrote that comment.
Martin Hohenberg
Was that edited part appended by you or Izzy?
Martin Hohenberg
yeah , it was appended by me to describe more clearly
lzyy
A: 
RewriteEngine on
RewriteRule ^(([0-9]{1,2})[0-9]*)$ /$2/$1.html

Greedy matching means that the first selector will pick up two characters if they are available.

However, I'm not sure that your rule makes much sense, as pages 14, 140-149 and 1400-1499 will be in the same directory. Might it make more sense to put 0-99, 100-199, etc in the same directory?

RewriteEngine on
RewriteRule ^([0-9]{1,2})$ /0/$1.html
RewriteRule ^(([0-9]+)[0-9]{2})$ /$2/$1.html
Andrew Aylett
my aim doing this is to avoid too many files within a folder , your rule makes sure there are no more then 100 files in a folder , it make more sense when there are so much files.
lzyy