How to rewrite a URL and pass on the original URL as a parameter

apache-2.2mod-rewrite

I'm building a site that needs to include a 'check' procedure, to do several initiation tasks for a user's session. Examples include checking whether they're accepting cookies, determining if their IP address grants them specific privileges, etc.

Once the check is complete, I need to redirect the user back to the page they originally requested.

The plan is to use RewriteCond and map all URLs to an 'initiator' if the user doesn't have a specific cookie set.

Let's say I want to rewrite all URLs (ultimately, with some conditions, of course) to:

/foo?original_url=...

Where the ... is the original URL requested, URL-encoded.

The closest I've got is this:

RewriteRule ^(.*)$ http://localhost/php/cookie.php$1 [R=301]

I can then inspect the original URL, captured in the backreference, via PATH_INFO. However, this is pretty messy – I would much prefer to pass that value as a URL parameter

Best Answer

see http://httpd.apache.org/docs/2.2/rewrite/flags.html#flag_qsa, which covers this exact use-case.

In short, use:

RewriteRule /pages/(.+) /otherpage?page=$1 [QSA,R=301,B]

The B should re-escape the original path.

Related Topic