Sparkup
Sparkup

Reputation: 3754

htaccess rewrite query string

I have the following .htaccess file

Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [L]

RewriteRule ^constant?([^/]+)=([^/]+) /index.php?url=constant&type=$1&task=$2 [L]

The last line isn't quite working or is being affected by the previous.

If $_GET['url'] doens't exist in DB it fires 404.

contan?x=y //gives 404
constant?x=y //works

That is how it shoud work.

However, when I use var_dump($_GET); on line 1 of index at example.com/constant?x=y

I only get array(1) { ["url"]=> string(8) "constant" }

Is the last line being affected by the previous, could someone point me in the right direction?

Upvotes: 0

Views: 3078

Answers (3)

LazyOne
LazyOne

Reputation: 165471

Use these rules:

Options +FollowSymlinks
RewriteEngine On

# specific rule
RewriteCond %{QUERY_STRING} ^([^=]+)=([^&]+)
RewriteRule ^(constant)$ /index.php?url=$1&type=%1&task=%2 [L]

# general catch-all
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [L]

You cannot match query string in rewrite rule: rewrite rule only matches path part of the URL while query string has to be matched via rewrite condition.

Obviously, this specific rule will not be triggered if you do not provide enough parameters, e.g. /constant or /constant?say=.


If you add QSA flag to that rule, then you will be able to pass other parameters as well (but it will pass whole query string over): e.g. /constant?say=meow&loud=yes will become /index.php?url=constant&type=say&task=meow&say=meow&loud=yes -- it can be useful depending on your URLs and tasks performed:

RewriteRule ^(constant)$ /index.php?url=$1&type=%1&task=%2 [QSA,L]

Upvotes: 1

Ofir
Ofir

Reputation: 415

Since you are using the L flag in the first rewrite rule, and since that rule always matches, you will never trigger the last rule.

Try to put the last rule before the first rule (and add the QSA as Jason McCreary said).

Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^constant?([^/]+)=([^/]+) index.php?url=constant&type=$1&task=$2 [L,QSA]
RewriteRule ^(.*)$ index.php?url=$1 [L]

Upvotes: 0

Jason McCreary
Jason McCreary

Reputation: 73031

You need to use the query string append flag, QSA, to ensure you pass the existing GET vars. Otherwise, they are overwritten by the RewriteRule

RewriteRule ^constant?([^/]+)=([^/]+) /index.php?url=constant&type=$1&task=$2 [L,QSA]

Upvotes: 3

Related Questions