Search code examples
apachemod-rewriteurl-rewritingrequest-uri

Rewrite rule and the_request


How to rewrite search/2 from index.php?search="x"&&searc_by="y"&page_no=2?

If I am not wrong %REQUEST_URI is search/2, right? Also what is %THE_REQUEST in this case.

The page where search/2 link is located is rewritten as just home_page.


Solution

  • %{REQUEST_URI} and %{THE_REQUEST} are variables in mod_rewrite. These variables contain the following:

    • %{REQUEST_URI} will contain everything behind the hostname and before the query string. In the url http://www.example.com/its/a/scary/polarbear?truth=false, %{REQUEST_URI} would contain /its/a/scary/polarbear. This variable updates after every rewrite.
    • %{THE_REQUEST} is a variable that contains the entire request as it was made to the server. This is something in the form of GET /its/a/scary/polarbear?truth=false HTTP/1.1. Since the request that was made to the server is static in the lifespan of one such request, this variable does not change when a rewrite is made. It is therefore helpful in certain situations where you only want to rewrite if an external request contained something. It is often used to prevent infinite loops from happening.

    A complete list of variables can be found here.


    In your case you will have a link to search/2?search=x&search_by=y. You want to internally rewrite this to index.php?search=x&search_by=y&page_no=2. You can do this with the following rule:

    RewriteRule ^search/([0-9]+)$ /index.php?page_no=$1 [QSA,L]
    

    The first argument matches the external request that comes in. It is then rewritten to /index.php?page_no=2. The QSA (query string append) flag appends the existing query string to the rewritten query string. You end up with /index.php?search=x&search_by=y&page_no=2. The L flag stops this 'round' of rewriting. It's just an optimalization thing.