netdon
netdon

Reputation: 45

Passing variables through htaccess with a rewrite rule

I'm trying to rewrite the following

http://example.com/somefile?variable=somevariable

to

index.php?processurl=/somefile?variable=somevariable

I understand I need to use [QSA] to pass the variables so I have written the following in my htaccess:

RewriteEngine On
RewriteBase /
RewriteRule ^(.*) index.php?processurl=/$1 [QSA]

However this RewriteRule doesn't seem to be passing the variable. All I get is index.php?processurl=/somefile

Upvotes: 4

Views: 3265

Answers (2)

Steven
Steven

Reputation: 6148

Problem

The problem is with your understanding of the QSA flag. What that does is appends the original query string to the redirected URL. This is useful in some circumstances where you wish to append another parameter (or more than one) to the query string.


**Example**

Given the URL:

 http://example.com/?var1=somevalue 

Then the rewrite rules:

 RewriteRule . /?var2=thisvalue
 RewriteRule . /?var2=thisvalue [QSA]

Would output:

 Rule 1 > http://example.com/?var2=thisvalue
 Rule 2 > http://example.com/?var2=thisvalue&var1=somevalue

The problem, in your case is that you don't want to append the query string as a query string you want to append it as a variable; if that makes sense...

Solution

The solution then is - as simple as it sounds - to append the query string as a variable...

You can do this with the use of the variable %{QUERY_STRING}:

 RewriteEngine On
 RewriteBase /
 RewriteRule ^(.*) index.php?processurl=/$1?%{QUERY_STRING}

Suggestion

As anubhava pointed out you might like to add:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

So that you don't accidentally wind up rewriting the wrong urls.

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) index.php?processurl=/$1?%{QUERY_STRING}

Upvotes: 1

anubhava
anubhava

Reputation: 784918

You can try this rule:

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?processurl=/$1 [QSA,L]

Upvotes: 2

Related Questions