开发者

htaccess rewrite query string

开发者 https://www.devze.com 2023-04-04 03:39 出处:网络
I have the following .htaccess file Options +FollowSymlinks RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f

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 开发者_JAVA技巧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?


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]


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]


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]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号