Kruga
Kruga

Reputation: 781

RewriteRule not working as expected with mod_rewrite

I'm making a website, just running from localhost with xampp at the moment. I'm using mod-rewrite to redirect everything to my index, which works so far.

# From  /somepage
# To    ?site=somepage
RewriteRule ^([^/\.\?=]+)/?$ ?site=$1 [L]

# From  /somepage=ID
# To    ?site=somepage&sub=ID
RewriteRule ^([^/\.\?=]+)=([^/\.\?]+)/?$ ?site=$1&sub=$2 [L]

But I also want to be able to add more query string variables at the end of the URL, so you can send or bookmark that link, while the redirection still works. I made something like this:

# From  /somepage?morevars
# To    ?site=somepage&morevars
RewriteRule ^([^/\.\?=]+)\?(.+) ?site=$1&$2 [L]

I have tried different variations for this, and also including conditions or merging it with another rule, but to no success. It seems like it is matching the first rule instead but I'm not sure.

Upvotes: 0

Views: 98

Answers (2)

AbsoluteƵERØ
AbsoluteƵERØ

Reputation: 7870

.htaccess is processed in order, so if Apache finds a match and you're using an [L] flag it stops since that is the Last command. The ? matches should not be needed because RewriteRule will see them as query strings and ignore them.

Note: Query String

The Pattern will not be matched against the query string. Instead, you must use a RewriteCond with the %{QUERY_STRING} variable. You can, however, create URLs in the substitution string, containing a query string part. Simply use a question mark inside the substitution string, to indicate that the following text should be re-injected into the query string. When you want to erase an existing query string, end the substitution string with just a question mark. To combine a new query string with an old one, use the [QSA] flag.

This should work.

RewriteRule ^([^/\.=]+)=([^/\.]+)/?$ ?site=$1&sub=$2 [L]
RewriteRule ^([^/\.=]+)/?$ ?site=$1 [QSA,L]

Upvotes: 2

Étienne Miret
Étienne Miret

Reputation: 6650

The pattern given to a RewriteRule is matched against the request URL-path. That is, the request URL without scheme, host, port and query string.

What you need is to add the [QSA] (query string append) flag to your first rule. See the reference documentation for RewriteRule.

Upvotes: 2

Related Questions