Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

apache - PHP: GET Variables on Mod Rewritten URL

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]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...