1

I have this rule:

RewriteEngine On
RewriteRule   ^/page/([a-zA-Z0-9]+)\?(.*)$    /index.php?page=$1&$2

It should take something like this:

/page/contact?cake=lie

and go to the page:

/index.php?page=contact&cake=lie

I've tested this with tools like RegExr and RegexPal, and it works there. But when putting it into Apaches config, visiting the url gives Apaches 404 page.

Can anyone help?

4 Answers 4

2

If you want to pass the existing query string verbatim, mod_rewrite provides the QSA flag for this purpose. Using it, your rule set could be simplified to the following:

RewriteEngine On
RewriteRule   ^/page/([a-zA-Z0-9]+)$    /index.php?page=$1 [QSA]

mod_rewrite will then automatically append any existing query string to the one that you've added via your replacement. The result is effectively the same as Steven Monai's approach, but I feel this method a bit cleaner.

2

By default mod_write matches against REQUEST_URI, which only contains the URI but not the dynamic parameters, so it will discard everything after question mark.

To match against full URI, you need to use THE_REQUEST instead (or if there's another method , please enlighten me!). Please note that it contains the full request the client sent, for example "GET /foo?bar=baz HTTP/1.1".

Try something like

RewriteCond %{THE_REQUEST} ^(.*)$
RewriteRule ^GET /page/([a-zA-Z0-9]+)\?(.*) HTTP.*$    /index.php?page=$1&$2
5
  • So this would be the only way to keep the GET parameters on a rewrite?
    – borntyping
    Nov 12, 2010 at 11:48
  • As far as I know, yes. But I might be wrong, too, since mod_rewrite truly is damned voodoo and its flexibility amazes me every time. :-) Nov 12, 2010 at 11:50
  • Ok, thanks. Any idea how I could get the parts of THE_REQUEST that I need?
    – borntyping
    Nov 12, 2010 at 12:19
  • It's late Friday afternoon and my brain activity is nearing zero, but I edited my reply. Try something like that. Nov 12, 2010 at 12:24
  • You can also access the query string with QUERY_STRING. Nov 12, 2010 at 15:42
0

Do you have rewrite engine turned on?

RewriteEngine On
1
  • Yes. Other rewrite rules are working, but are disabled while I make this work.
    – borntyping
    Nov 12, 2010 at 11:22
0

Janne's assessment of why your rule doesn't work is correct. But I would take a less complicated approach to solve it:

RewriteRule ^/page/([a-zA-Z0-9]+)$ /index.php?page=$1&%{QUERY_STRING}

There's no need to pick apart the raw request to get at the query string when Apache already gives it to you in %{QUERY_STRING}.

The list of server variables available to you via the %{VARNAME} syntax is documented here.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .