How to Get mod_rewrite to Work With Forms

I’ve been developing a new Web site that uses Apache‘s mod_rewrite to make “pretty” URLs instead of exposing both the script name and parameters to the end user.  For example, instead of seeing a URL like http://blahblahblah.com/somepage.php?page_id=details, the end user sees http://blahblahblah.com/details.

Now, the first head-scratcher of a problem I ran into is that to do this particular for of rewriting results in the page_id parameter being passed to the PHP script as part of a GET  request.   This means that if we need to do any sort of form that references the rewritten URL, you need to either have that form submit it’s values as a POST or find a way to append the form’s details to the GET request generated by mod_rewrite.

From Well House Consultants:

Passing GET parameters through Apache mod_rewrite

If you’re using Apache mod_rewrite to redirect a series of URLs to a single script, did you know that you can pass values entered onto a form via the GET method through as well? Simply add on %{QUERY_STRING} onto the end of your new URL. You’ll need to add a ? into the target URL to ensure that the query string is taken as such …. and you can even add more parameters if you wish.

Here’s how we divert all requests to .htm, .html, .php, .php4 and .php5 files in a directory to a single script called b.php; we pass in any parameters the user filled in on his web page, and we generate an extra request parameter called pagename that contains … of course … the name of the page requested.

RewriteEngine On
RewriteRule ^(.*)\.htm b.php?pagename=$1&%{QUERY_STRING}
RewriteRule ^(.*)\.php b.php?pagename=$1&%{QUERY_STRING}


Posted

in

by

Comments

2 responses to “How to Get mod_rewrite to Work With Forms”

  1. Marc Avatar

    thanks, this is just what I was looking for.

  2. jack Avatar
    jack

    THAAAANKS!

    I saw people struggling going some complicated ways to get that simple while I was googeling.

Leave a Reply to jack Cancel reply

Your email address will not be published. Required fields are marked *