bakingsoda
bakingsoda

Reputation: 57

Simple Apache Rewrite Issue Passing Variables

For some reason I'm having an issue with a rewrite rule that I assume should be very easy.

I would like to rewrite site.com/page.html?1 to site.com/page.php?p=1 and site.com/page.html to site.com/page.php

here is what I assumed should work, but doesn't:

RewriteRule page.html?([^/\.]+)/?$ page.php?p=$1 [L,QSA]

Upvotes: 0

Views: 47

Answers (2)

Jonathan Kuhn
Jonathan Kuhn

Reputation: 15301

The query string (portion of URL after the ?) is not included in the regex portion of a RewriteRule. Just the requested page path/name. If you want to capture the query string you would need to use a RewriteCond and capture the %{QUERY_STRING} environment variable. Something like this:

RewriteCond %{QUERY_STRING} (\d*)
RewriteRule page.html page.php?p=%1 [L,QSA]

Notice, I now capture the query string in the RewriteCond, removed the trailing ?... from the end of the regex in RewriteRule and also changed the variable in the replace with %1 instead of $1 to refer to the captured condition instead of rule. You can also change the regex in the condition to better match what you want.

Edit: Also, keep in mind that the QSA will append any query string not already present in the rewritten URL. So if you leave that in there, if you are passing a query string like ?1, you will still get a key appended to the URL of 1 with an empty value (?1 => array(1=>'')). If you don't need additional query string values, just remove QSA or if you want the extra values and don't care about blank query string parameters (doesn't hurt unless you are looping over all of $_GET), then leave it in there.

Upvotes: 2

Rob W
Rob W

Reputation: 9142

If the value of p is always an integer, try:

RewriteRule page\.html\?([\d]+)$ page.php?p=$1 [L,QSA]

Tested on https://regex101.com/r/3AFu0A/1

Upvotes: -1

Related Questions