Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I mod_rewrite and keep query strings?

I want to mod_rewrite a URL to another page, but then I also want any query strings added to be preserved.

RewriteEngine On  #enforce trailing slashes RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_URI} !# RewriteCond %{REQUEST_URI} !(.*)/$ RewriteRule ^(.*)$ http://localhost/siteroot/$1/ [L,R=301]  RewriteRule ^apps/([A-Za-z0-9-_]+)/?$ index.php&app=$1 

So if a user visits apps/app1/, index.php?app=app1 is shown. However, I want to be able to preserve optional query strings, so that visiting apps/app1/?variable=x returns index.php?app=app1&variable=x.

What mod_rewrite rule/condition would make this happen?

like image 696
Daniel Oakey Avatar asked Oct 13 '12 12:10

Daniel Oakey


People also ask

What is mod_rewrite used for?

mod_rewrite lets you create all sorts of rules for manipulating URLs. For example, you can insert values pulled from the requested URL into the new URL, letting you rewrite URLs dynamically.

What is mod_rewrite?

mod_rewrite is an Apache module that allows for server-side manipulation of requested URLs. mod_rewrite is an Apache module that allows for server-side manipulation of requested URLs. Incoming URLs are checked against a series of rules. The rules contain a regular expression to detect a particular pattern.

Where is mod_rewrite so?

The mod_rewrite module is enabled by default on CentOS 7. If you find it is not enabled on your server, you can enable it by editing 00-base. conf file located in /etc/httpd/conf. modules.


1 Answers

You need to add the [QSA] flag ("query string append")

RewriteRule ^apps/([A-Za-z0-9-_]+)/?$ index.php&app=$1 [L,QSA] 

For page 301 redirects with the [R] flag as opposed to internal rewrites like this one, the query string is automatically appended. However, you must force it with [QSA] for the internal rewrite.

like image 83
Michael Berkowski Avatar answered Sep 26 '22 20:09

Michael Berkowski