1

I'm fairly new to mod_rewrite and I'm trying to get the RewriteMap directive to work properly. I would appreciate your help in using it.

Our URL format is as follows:

example.com/section.php?xSec=[ID]

So for section 201, which is 'Apple iPads' the URL is:

example.com/section.php?xSec=201

What I'm wanting is to rewrite this to:

example.com/apple-ipads

I have defined the RewriteMap txt file in apache config, using the following line:

RewriteMap sections txt:/var/www/rewrites/sections.txt

This txt file contains the following:

multifunction-printers 102
inkjet-printers 103
laser-printers 104
apple-ipads 201

I have attempted the following rewrite rule in .htaccess:

RewriteRule ^/section.php?xSec=(.*) ${sections:$1}

Which doesn't work. I'm assuming that there is either an issue with my RewriteRule or I've put the RewriteMap directive in the wrong place in the config file. Any suggestions?

Thanks in Advance

Daniel

Daniel Kilburn
  • 167
  • 1
  • 4
  • 13

2 Answers2

1

You could use this rewrite:

RewriteRule ^/(.*) /section.php?xSec=${sections:$1|NOTFOUND}

For every request sent to:

example.com/apple-ipads

You should see transparently the answer come from:

example.com/section.php?xSec=201

In case the key is not found, the answer come from:

example.com/section.php?xSec=NOTFOUND

But you must know that this rewrite could not work, for example when you have a space or other characters (àèò...) that can be encoded by the browser.

freedev
  • 25,946
  • 8
  • 108
  • 125
0

your map is backwards. the key should be listed first.

201 apple-ipads

I believe you shouldn't include the / at the beginning of the pattern, plus a few other things; i.e., assuming your IDs are numbers only, a better pattern would be:

RewriteRule  ^section\.php\?xSec=(\d+)$  ${sections:$1}  [nocase]


Update

I've just had to do some htaccess work with uri's where I needed to grep the query strings. this excellent post helped greatly. the previous pattern won't work. this one should:

RewriteCond   %{QUERY_STRING}   xSec=(\d+)$   [nocase]
RewriteRule   ^section\.php$   ${sections:%1}?  [nocase,redirect=perm,last]

If you want to default to using the original query string when the key can't be matched (untested):

RewriteCond   %{QUERY_STRING}   xSec=(\d+)$   [nocase]
RewriteRule   ^section\.php$   ${sections:%1?|$0?id=%1}  [nocase,redirect=perm,last]


Update 2

The syntax in the last example is wrong because of the ? inside the matching side of the ${} function. I've since updated my own rules using something like this:

# mapped
RewriteCond   %{QUERY_STRING}   xSec=(\d+)$   [nocase]
RewriteCond   ${sections:%1|NOTFOUND}   !NOTFOUND   [nocase]
RewriteRule   ^section\.php$   ${sections:%1}?  [nocase,redirect=perm,last]

Using this set of rules, only uri's with mapped (query) keys would get redirected.

Cheers.

Community
  • 1
  • 1
Gregory
  • 101
  • 1