URL Rewrite GET parameters

I want my url to look like the following

www.website.com/home&foo=bar&hello=world

I only want the first get parameter to change

However the actual "behind the scenes" url is this

www.website.com/index.php?page=home&foo=bar&hello=world

All tutorials I find change all of the parameters.

Any help much appreciated!


Solution 1:

Add this to your .htaccess in your web root / directory

RewriteEngine on
RewriteBase /

RewriteRule ^home$ index.php?page=home&%{QUERY_STRING} [NC,L]

If you want this to work for all pages i.e. /any-page gets served as index.php?page=any-page then use

RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d # not a dir
RewriteCond %{REQUEST_FILENAME} !-f # not a file
RewriteRule ^(.*)$ index.php?page=$1&%{QUERY_STRING} [NC,L]


How do these rules work?

A RewriteRule has the following syntax

RewriteRule [Pattern] [Substitution] [Flags]

The Pattern can use a regular expression and is matched against the part of the URL after the hostname and port (with the .htaccess placed in the root dir), but before any query string.

First Rule

The pattern ^home$ makes the first rule match the incoming URL www.website.com/home. The %{QUERY_STRING} simply captures and appends anything after /home? to the internally substituted URL index.php?page=home.

The flag NC simply makes the rule non case-sensitive, so that it matches /Home or /HOME as well. And L simply marks it as last i.e. rewriting should stop here in case there are any other rules defined below.

Second Rule

This one's just more generic i.e. if all of your site pages follow this URL pattern then instead of writing several rules, one for each page, we could just use this generic one.

The .* in the pattern ^(.*)$ matches /any-page-name and the parentheses help capture the any-page-name part as a $1 variable used in the substitution URL as index.php?page=$1. The & in page=home& and page=$1& is simply the separator used between multiple query string field-value pairs.

Finally, the %{QUERY_STRING} and the [NC,L] flags work the same as in rule one.