rewriterule not working

Terminology

I think you have some terminology a little mixed up:

  • A URL “rewrite” alters the endpoint of a HTTP request. If http://example.com/param/exam1 really serves content from http://example.com/examples/exam1?get=param, then the former is being rewritten to the latter (though not necessarily visible to the end-user).
  • In the world of URL-rewriting, a “redirect” is a rewrite that (instead of serving the request from the altered endpoint) kicks back a HTTP 300-range status code, telling the client that sent the HTTP request to send a new request to the rewritten URL (thus altering the address visible to the end-user). If a user enters http://example.com/param/exam1 in their address bar, and then the browser is forwarded to http://example.com/examples/exam1?get=param, then the former will have been redirected to the latter.

RewriteRule Analysis

At a glance, I would suspect that your RewriteRule is never matching your URLs; or if it is, not rewriting them as you might expect:

RewriteRule ^(exam1|exam2)/([^/]+)/?$ /example/$2/?get=$1 [QSA,L]
  • Match HTTP request paths:
    • ^(exam1|exam2)/: beginning with exam1/ or exam2/ and capture exam1/exam2 as sub-group $1
    • ([^/]+): …followed by 1 or more non-/ characters, which will captured as sub-group $2
    • /?$: …possibly followed by a / at the very end.
  • Redirect matched request paths to /example/$2/?get=$1

In practice:

  • A request sent to http://example.com/param/exam1 will not be rewritten as the request path begins with param/ and not exam1/ or exam2/
  • A request to http://example.com/exam1/param/ will be rewritten to be served by the endpoint http://example.com/example/param/?get=exam1
  • A request to http://example.com/exam1/param/test will not be rewritten because the request path does not end at the first path segment after exam1 or exam2

Solution

To rewrite the URL you’ve specified, you need to swap the capture groups in your Regex:

RewriteRule ^([^/]+)/(exam1|exam2)/?$ /example/$2/?get=$1 [QSA,L]

This will match path segments in the desired order and correct your back-references. However, this rule comes with some strange caveats that could cause unexpected behaviors. In practice, requests to:

  • http://example.com/foo/exam1 => http://example.com/example/exam1?get=foo
  • http://example.com/bar/exam1/ => http://example.com/example/exam1?get=bar
  • http://example.com/posts/exam2_announcement => http://example.com/example/exam2?get=posts
  • http://example.com/tests/exam120 => http://example.com/example/exam1?get=tests