chaoskreator
chaoskreator

Reputation: 914

htaccess - optional url parameter for redirect

I have a redirect for an url in my htaccess file that works just like it should:

RewriteRule (.*)/(.*)\.html$ view.php?mode=$1&id=$2 [nc]

However when I modify the line to try to check for the existence of the start parameter (?start=1) with the line below, I get a 404.

RewriteRule (.*)/(.*)\.html(\?start=[0-9]+)$ view.php?mode=$1&id=$2&start=$5 [nc]

How should I write this to obtain the optional start parameter and add it to the URI?

Upvotes: 0

Views: 371

Answers (1)

Jon Lin
Jon Lin

Reputation: 143906

You can't match against the query string (everything after the ?) in a RewriteRule, you need to match against the %{QUERY_STRING} in a RewriteCond and use the %N to backreference grouping:

RewriteCond %{QUERY_STRING} ^start=([0-9]+)
RewriteRule (.*)/(.*)\.html$ view.php?mode=$1&id=$2&start=%1 [nc]

But, you don't need to do this. To append an existing query string just use the QSA flag:

RewriteRule (.*)/(.*)\.html$ view.php?mode=$1&id=$2 [nc,QSA]

And if the URI is /something/file.html?start=100, it'll be rewritten to /view.php?mode=something&id=file&start=100

Upvotes: 1

Related Questions