Forum Moderators: phranque

Message Too Old, No Replies

How to match the first occurrence of a regular expression in .htaccess

.htaccess regular expression matching

         

caruso_g

4:49 pm on Jan 8, 2010 (gmt 0)

10+ Year Member



Hi all,
I am trying to match a url to rewrite it in my .htaccess file with no luck.
Basically, I need to rewrite old links to posts like:

http://www.example.com/index.php?option=com_content&task=view&id=132&Itemid=2&Itemid=2

to

http://www.example.com/132

where the post number is the id value in the first address and can be from 1 to 5 digits.
In my .htaccess file I tried, with no luck, the following:

RewriteEngine On
RewriteBase /

RewriteRule &id=(\d{1,5}) /$1 [R=301,NC]

RewriteRule ^(\d{1,5})/?$ /?p=$1 [NC,L]

Can you help me? I am not able to find the error.
Thanks a lot.

jdMorgan

5:29 pm on Jan 8, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



RewriteRule cannot "see" query strings.

Use a RewriteCond to examine %{QUERY_STRING}, as in:


RewriteCond %{QUERY_STRING} ^([^&]*&)*id=([0-9]{1,5})(&.*)?$
RewriteRule ^(index\.php)?$ /?p=%2 [NC,L]

Note however that your rule does not rewrite to the filepath you mentioned above, and neither does this one. It is intended to correct the code your wrote and won't necessarily do what you said you wanted to do above.

Jim

caruso_g

5:56 pm on Jan 8, 2010 (gmt 0)

10+ Year Member



Thanks a lot, it worked perfectly.
can I also ask you to explain me some portion of the code to understand them?

RewriteCond %{QUERY_STRING} ^([^&]*&)*id=([0-9]{1,5})(&.*)?$
RewriteRule ^(index\.php)?$ /?p=%2 [NC,L]

1 - ([^&]*&)* = zero or more groups of characters that are not "&" followed by a "&" (btw, wonderful!)?
2 - Is the use of "%" better then "$"?

About my code, since WP posts are written like "/?p=#*$!x" where #*$!x is the id post number,
I added the second rule:


RewriteRule ^(\d{1,5})/?$ /?p=$1 [NC,L]

to overwrite what I was trying to rewrite (i.e. /?queryString&id=nnnn$anotherQuery to /nnnn and then to /?p=nnnn) to make it simpler for visitors to remember it.

Anyway, thanks a lot.

Is there a simple reference to study for that RewriteCond?

[edited by: jdMorgan at 2:48 am (utc) on Jan. 9, 2010]
[edit reason] Disabled smilies in post. [/edit]

g1smd

9:14 pm on Jan 8, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



The Apache manual should be the first port of call as the official point of reference.

jdMorgan

2:42 am on Jan 9, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Note that "\d" is Apache 2 only. Apache 1.x must use "[0-9]".
Apache 2 supports PCRE, Apache 1 is POSIX regex only.

Jim