views:

70

answers:

3

I need to match two cases

js/example_directory/example_name.js 

and

js/example_directory/example_name.js?12345  

(where 12345 is a digit string of unknown length and the directory can be limitless in depth or not exist at all)

I need to capture in both cases everything between js/ and .js
and if ? exists capture the digit string after ?

This is what I have so far

^js/(.*).js\??(\d+)?

This works except it also captures

js/example_directory/example_name.js12345 

I want the regex to ignore that. Any suggestions?
Thank you all!

Test your patterns here

Answer:
Using Gumbo's information my final rewrite rule is as follows.

<IfModule mod_rewrite.c>
 RewriteEngine on
 RewriteBase /
 RewriteCond %{SCRIPT_FILENAME} !-d
 RewriteCond %{SCRIPT_FILENAME} !-f
 RewriteCond %{QUERY_STRING} ^\d*$
 RewriteRule ^js/(.*)\.js$ js.php?f=$1.js&v=%0 [L]
</IfModule>
+4  A: 

Include the whole querystring pattern, including the ? in one conditional match.

^js/(.*).js(\?\d+)?
John Weldon
+3  A: 

mod_rewrite’s RewriteRule directive does only test the URI path and not the query. So using a rule like the following does already match both URIs:

RewriteRule ^js/(.*)\.js$ …

If you now want to test the query too, you need to use an additional RewriteCond:

RewriteCond %{QUERY_STRING} ^\d*$
RewriteRule ^js/(.*)\.js$ …

The match of the last successful RewriteCond can be referred to with %n, so in case of the whole match %0 or in this case even just %{QUERY_STRING} directly.

Gumbo
Gumbo, is there a way to make the rewrite condition, optional. Like this; if query exists be numeral, if does not exist proceed anyway.
Mohammad
I also don't understand the comment you made about %n if you would please offer more information on that I would be grateful.
Mohammad
@Mohammad: Using `^\d*$` does already allow an empty query; but if, it needs to be numeric. And `%n` (where *n* is a number in 0–9) is used to reference the match of the whole regular expression (`%0`) or just the match of a specific group (`%n` is the match of the n-th group).
Gumbo
Gumbo, thank you! I've updated the question with the final rule I used. Please see if there is any need for improvement. And thanks again.
Mohammad
+1  A: 

As far as regular expressions go - you can use the (?:) (non capture grouping) to make the \?(\d+) as a chunck, optional like so:

^js/(.*).js(?:\?(\d+))?

You really don't >need< to use the ?: (non capture) portion, but if you don't, back references will be changed - 1 will point at the filename, 2 will point at ?1234 and 3 will be 1234

gnarf