.htaccess漂亮的url,它也允许正常的get参数

时间:2014-08-22 15:08:18

标签: apache .htaccess mod-rewrite

我有以下.htacess代码,允许三个$ _GET参数以漂亮的方式显示

RewriteRule ^search/([a-zA-Z0-9-_%]+)/([a-zA-Z0-9-_%]+)/([a-zA-Z0-9-_%]+)/(.*)$ search.php?name=$1&city=$2&age=$3 [L]
RewriteRule ^search/([a-zA-Z0-9-_%]+)/([a-zA-Z0-9-_%]+)/(.*)$ search.php?name=$1&city=$2 [L]
RewriteRule ^search/([a-zA-Z0-9-_%]+)/(.*)$ search.php?name=$1 [L]

网址将类似于domain.com/search/name/city/age

但我想添加更多动态过滤器,例如domain.com/search/name/city/age?gender=male

现在我的.htaccess不会将?gender=male视为正常获取参数。如果我使用print_r($_GET)在php中打印所有$ _GET值,它将只向我显示我在.htaccess中写的$ _GET值

可能是什么解决方案?

1 个答案:

答案 0 :(得分:0)

您必须使用%{QUERY_STRING}来匹配?gender=male 此外,您可以将([^/]+)(除了斜杠/之外的每个字符)替换为更通用的模式。

以下是使用gender

捕获/search/name/city/age?gender=something的示例
RewriteEngine On

RewriteCond %{QUERY_STRING} ^gender=([^&]+)$
RewriteRule ^search/([^/]+)/([^/]+)/([^/]+)/?$ /search.php?name=$1&city=$2&age=$3&gender=%1 [L]

RewriteRule ^search/([^/]+)/([^/]+)/([^/]+)/?$ /search.php?name=$1&city=$2&age=$3 [L]
RewriteRule ^search/([^/]+)/([^/]+)/?$ /search.php?name=$1&city=$2 [L]
RewriteRule ^search/([^/]+)/?$ /search.php?name=$1 [L]

编辑:带QSA标志的简易版(追加查询字符串)

RewriteEngine On

RewriteRule ^search/([^/]+)/([^/]+)/([^/]+)/?$ /search.php?name=$1&city=$2&age=$3 [L,QSA]
RewriteRule ^search/([^/]+)/([^/]+)/?$ /search.php?name=$1&city=$2 [L,QSA]
RewriteRule ^search/([^/]+)/?$ /search.php?name=$1 [L,QSA]