views:

204

answers:

1

I work for a company that used to have a polocy of obfuscating URLs for articles which you needed to register to use. So they would have something like

/story.php?story_id=Z_ZXYZ

which there was some code which mapped letters to numbers to work out the true story id

so

Z = 0 
Y = 1
X = 2

etc.

We are now moving technology stack and have decided that obfuscated urls are not needed. So I am looking at whether it is possible to un obfuscate the URLs using mod rewrite

So far I have

  RewriteCond %{REQUEST_URI} ^.*story.php [NC]
  RewriteCond %{QUERY_STRING} ^.*story_id=Z_([ZXYWVUTSRQ]*) [NC]
  RewriteRule ^.*$ /story/${decryptmap:%1} [L,R=301]

I have a rewrite map in the httpd.conf file

<IfModule mod_rewrite.c>
  RewriteMap decryptmap txt:decyrpsdstxt
</IfModule>

Which has content

##
## decrypt urls
##
Z 0
X 1

etc..

but it dosn't seem to be working, even if I put some text in the Rewriterule as so RewriteRule ^.*$ /story/${decryptmap:ZXY} [L,R=301] I get a url like /story/?story_id=Z_ZAD

Is there anything obvious I am doing wrong? I can see that the two conditions are being matched but the map doesn’t seem to work.

Should I even be trying to get mod rewrite to do this? I could redirect to a script which did this fairly easily but that would put redirect code in two places which I didn't like the idea of.

(I'm not worried about the ?story_id=Z_ZAD, I know how to get rid of that)

+1  A: 

A rewrite map would work with the whole string that has been passed. So in your case you would need to pass just one character at a time:

# put story_id at the begin for efficiency
RewriteCond %{QUERY_STRING} ^(([^&]*&)+)(story_id=Z_[^&]*)&*(.*)$
RewriteRule ^story\.php$ story.php?%3&%1%4

# decrypt story_id value character by character
RewriteCond %{QUERY_STRING} ^story_id=Z_([^ZXYWVUTSRQ]*)([ZXYWVUTSRQ])(.*)
RewriteRule ^story\.php$ story.php?story_id=Z_%1${decryptmap:%2}%3 [N]

# redirect
RewriteCond %{QUERY_STRING} ^story_id=Z_([^&])&*(.*)
RewriteRule ^story\.php$ /story/%1?%2 [L,R=301]
Gumbo
alternatively, he could use script that would just get the map and pair it with the correct URL, if mod_rewrite wouldn't work.
dusoft
@dusoft: Yes, absolutely. In fact, the rewrite map type `txt` uses linear search and thus O(n). But ten items is not a problem. For a larger amount of items the type `dbm` is a better choice since that is implemented with a hash map (O(1)).
Gumbo
I got this to work using 301 redirects at each stage I think some of my other rules were breaking it.
Jeremy French