.htaccess 301 和 PHP 查询字符串

.htaccess 301 and PHP query string

我想知道 SO 社区的精彩世界是否可以帮助我解决这个问题。

我有以下 URL 我想 redirect/rewrite 在我的 .htaccess 文件中。

1。重定向

我正在尝试 301 重定向 URL:

http://example.com/staff-view.php?i=ACCOUNT_ID_EXAMPLE

http://example.com/staff-view/ACCOUNT_ID_EXAMPLE/

我尝试了以下操作:

RewriteEngine On

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+staff-view\.php\?i=([^\s]+) [NC]
RewriteRule ^ /staff-view/%1/? [R=301,L]

然而,当导航到来自 URL 时,它不会重定向。

2。 PHP 查询字符串

我正在使用以下重写:

RewriteRule ^staff-view/([^/]+)/?$ /staff-view.php?i= [L,QSA,NC]

并通过 URL

访问
http://example.com/staff-view/ACCOUNT_ID_EXAMPLE/

它正确地将我引导到正确的页面,但是当我尝试通过以下方法访问 ACCOUNT_ID_EXAMPLE 时:

<?
var_dump($_REQUEST);
var_dump($_GET);
?>

它们都是空的:

array(0) { } array(0) { }

如有任何帮助,我将不胜感激,如果您需要更多信息,请告诉我。


更新 1

已更新 .htaccess 文件:

RewriteEngine On

RewriteRule ^staff/([^/]+)/?$ /staff-view.php?i= [L,QSA,NC]

RewriteBase "/"

RewriteCond %{REQUEST_URI}  ^staff-view\.php$
RewriteCond %{QUERY_STRING} ^i=([A-Z0-9_]*)$
RewriteRule ^(.*)$  ^staff/%1/

我试图从以下位置访问文件:

http://example.com/path/to/site/staff/ACCOUNT_ID

它不起作用。但是,如果我从以下位置访问文件:

http://example2.com/staff/ACCOUNT_ID

有效。

但是如果我转到 http://example2.com/staff-view.php?i=ACCOUNT_ID 它不会重定向到 http://example2.com/staff/ACCOUNT_ID - 这不是世界末日,但我想修复它,但深层目录问题作为优先级 :).

试试这个:

RewriteEngine On
RewriteRule ^staff-view/([^/]*)$ /staff-view.php?i= [L]

尝试解析 %{THE_REQUEST}(例如,"GET /staff-view.php?i=account_id HTTP/1.1")以提取路径和查询字符串可能有效,但它不必要地复杂。我认为使用两个利用服务器变量 %{REQUEST_URI}%{QUERY_STRING} 的重写条件要简单得多,因为它们预先填充了您感兴趣的信息。

尝试以下操作:

RewriteEngine On

#If you don't have this set in your htaccess, 
#  Apache may prepend the final path with your on disk dir structure
RewriteBase "/"

#Rewrite if the /staff-view.php page is requested
RewriteCond %{REQUEST_URI}  ^/staff-view\.php$

#Rewrite if the query string contains i parameter anywhere. Assumes
#  ID can be only digits; include all allowed chars. eg: [a-zA-Z0-9_]    
#Don't forget the '&' before {{QUERY_STRING}} otherwise the match
#  will fail if i is the first parameter
RewriteCond &%{QUERY_STRING} &i=([0-9]+)

#Rewrite the account ID as part of the path. Append the query string
#  in order to preserve other query parameters (eg: if user asked for
#  /staff-view.php?i=123&x=boo, you want to preserve x=boo.  a 301
#  redirect tells the browser to go to the new path and to remember it
#This will stop processing and cause the browser to make a new request
RewriteRule ^(.*)$  /staff-view/%1/ [QSA,R=301,L]

#Finally, we want to silently forward any request matching the last
#  redirect target to the actual file that will serve the request. 
#  The account ID should be of the same format as above: ([0-9]+).  The
#  [L] flag tells the server to stop looking for new instructions
RewriteRule ^staff-view/([0-9]+)/$ /final.php?i= [QSA,L]

逻辑很容易遵循:如果请求的路径是 /staff-view.php,并且如果查询字符串包含 i 参数,则告诉用户的浏览器转至 /staff-view/ID ,保留其他查询参数。最后,当浏览器请求这个新路径时,静默地(不告诉浏览器)将请求连同 ID 和其他查询参数

转发给 final.php