问题
I'm trying to pass parameters and use the GET
function in PHP on a URL that has already been rewritten using mod rewrite.
I have this in my HTACCESS file:
Options +FollowSymlinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^-]*)/$ ?action=$1 [L]
RewriteRule ^search/$ ?action=search [L]
If I have a URL like http://www.example.com/search/?q=test
I'm unable to get any of the parameters which I suspect is due to me already rewriting the URL!?
I've tried using the QSA
flag like below but still haven't been able to get it working.
RewriteRule ^search/?$ ?action=search [L,QSA]
回答1:
You need to update your RewriteRules to use the QSA (Query String Append) flag (without the ?
character in the rule):
RewriteRule ^search/$ ?action=search [L,QSA]
The QSA
flag tells Apache to preserve anything appended to the URL:
When the replacement URI contains a query string, the default behavior of RewriteRule is to discard the existing query string, and replace it with the newly generated one. Using the [QSA] flag causes the query strings to be combined.
Consider the following rule:
RewriteRule "/pages/(.+)" "/page.php?page=$1" [QSA]
With the
[QSA]
flag, a request for/pages/123?one=two
will be mapped to/page.php?page=123&one=two
. Without the[QSA]
flag, that same request will be mapped to/page.php?page=123
- that is, the existing query string will be discarded.
In addition, the ^search/$
rule is never reached, because it is overridden by this one: RewriteRule ^([^-]*)/$ ?action=$1 [L]
(which has the L
flag). You need to update your entire .htaccess
file as follows:
Options +FollowSymlinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteRule ^search/$ ?action=search [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^-]*)/$ ?action=$1 [L,QSA]
回答2:
With QSA
flag, you should swap bottom 2 rules with an additional condition in search
rule:
Options +FollowSymlinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{QUERY_STRING} (?:^|&)action=search(?:&|$) [NC]
RewriteRule ^search/?$ ?action=search [L,QSA,NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ ?action=$1 [L,QSA]
来源:https://stackoverflow.com/questions/35502265/php-get-variables-on-mod-rewritten-url