3

I want http://server/path/app.json?a=foo&b=bar to map to http://server/path/foo.php?a=foo&b=bar using mod_rewrite. I have the following incantation in my .htaccess which doesn't give any joy

RewriteEngine On
RewriteRule ^([^.?]+).json(.*)$ $1.php$2 [L]

Suggestions?

Update: Adding rewrite.log and error.log output (comments don't allow formatting)

I get the following in the rewrite.log

strip per-dir prefix: /Users/user/Sites/dir/app.json -> app.json
applying pattern '^([^.?]+).json(.*)$' to uri 'app.json'
rewrite 'app.json' -> 'app.php'
add per-dir prefix: app.php -> /Users/user/Sites/dir/app.php
internal redirect with /Users/user/Sites/dir/app.php [INTERNAL REDIRECT]

and the apache server log says

The requested URL /Users/user/Sites/dir/app.php was not found on this server.
punkish
  • 13,598
  • 26
  • 66
  • 101

1 Answers1

3

If I read your question correctly you want:

http://server/path/app.json?a=foo&b=bar

Going to:

http://server/path/foo.php?a=foo&b=bar

Sowhen you capture (app).json $1 is app and $2 is your second parenthesis, it's ... nothing (the part between json and the ?). As everything after the question mark is the QUERY STRING and cannot be captured here. Your rewriteRule is working on the requested file, not on the QUERY STRING. So you didn't captured foo anywhere. For the QUERY_STRING you could use the [QSA] flag on the rewriteRule, that would simply append a=foo&b=bar after your rewrite.

RewriteEngine On
RewriteRule ^([^.?]+).json(.*)$ $1.php$2 [L]

Here you tell apache to reuse $1 (the filename without .json), so app.json will get redirected to app.php, not foo.php.

RewriteEngine On
RewriteRule ^([^.?]+).json(.*)$ $1.php [L,QSA]

Will redirect app.json?a=b&z=r to app.php?a=b&z=r.

Now if you really need to capture foo as the first QUERY_STRING parameter the rule will become harder. But you could do it like that (here instead of the first parameter I detect the parameter 'a=' and capture his value in %4):

RewriteCond %{QUERY_STRING} (.*)(^|&|%26|%20)a(=|%3D)([^&]+)(.*)$
RewriteRule ^([^.?]+).json$ %4.php? [L,QSA]
regilero
  • 29,806
  • 6
  • 60
  • 99