Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add additional URL variables to a URL already rewritten with mod_rewrite

Does anyone have any idea if it is possible to put additional variables into a URL that you are using mod_rewrite to basically chop up into variables.

For example, if I have the URL:

website.com/post/53/post-title/

and I am using mod_rewrite to turn it into:

website.com/post.php?postid=53

Is there and elegant way to put additional variables into the "pre-rewritten" URL and keep them for my post.php script?

I.E., what if I create a link like the following:

website.com/post/53/post-title/?anothervar=6

So far it seems like my mod_rewrite code is just throwing out the additional variable and sending the URL to the post.php script like this:

website.com/post.php?postid=53

I do know that I can use $_SERVER['REQUEST_URI'] to get the original URL in my php script (AKA website.com/post/53/post-title/?anothervar=6) before it gets rewritten by mod_rewrite and then just chop up the string to get that added on variable, but I just wanted to know if there was a more elegant solution that solely used mod_rewrite.

like image 532
billmalarky Avatar asked Sep 03 '11 20:09

billmalarky


People also ask

How do you append a variable in URL?

To add a URL variable to each link, go to the Advanced tab of the link editor. In the URL Variables field, you will enter a variable and value pair like so: variable=value.

What is rewrite condition?

The RewriteCond directive defines a rule condition. One or more RewriteCond can precede a RewriteRule directive. The following rule is then only used if both the current state of the URI matches its pattern, and if these conditions are met.


2 Answers

you can also use %{QUERY_STRING} to pass original query string to new url. or use it as you wish e.g.

RewriteRule /pages/(.*) /page.php?page=$1&%{QUERY_STRING} [R]
like image 52
jancha Avatar answered Oct 21 '22 11:10

jancha


http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewriterule

"qsappend|QSA"

Use, QSA to make mod_rewrite properly "merge" additional arguments when rewriting.

RewriteRule /pages/(.+) /page.php?page=$1 [QSA] 

That will add "page=$1" to whatever request the user made.

PS. Although take care, because mod_rewrite will happily overwrite "page" though if the user specifies it. No way around it that I know off.

like image 28
Andreas Avatar answered Oct 21 '22 11:10

Andreas