首页 > 解决方案 > 如何在 .htaccess 中访问 query_string 中的键和值以在更改后的 url 中使用它们?

问题描述

我正在尝试使用获取参数转换 url

localhost:8080/goto/?fruits=1&apples=2

进入

localhost:8080/fruits/1/apples/2

使用以下命令:

RewriteEngine On    
RewriteCond %{QUERY_STRING} !apples [NC]

我可以验证访问的 url 是否具有键 apples、fruits 或附加的任何 get 参数,以区分具有不同键的多个 url,例如 berrys=1 或 melons=7 等。

使用以下命令

RewriteRule ^ fruits/([^/]*)/apples/([^/]*)$ goto/index.php?fruits=$1&apples=$2 [L]

我可以将 url localhost:8080/fruits/1/apples/2 更改为 localhost:8080/fruits/1/apples/2

如何优化 RewriteCond 中的命令以在 RewriteRule 中使用多个键和值作为 $1、$2 等而不对多行进行硬编码?不像:

RewriteEngine On  
RewriteCond %{QUERY_STRING} !apples [NC]
RewriteRule ^fruits/([^/]*)/apples/([^/]*)$ goto/index.php?fruits=$1&apples=$2 [L]
RewriteCond %{QUERY_STRING} !melons [NC]
RewriteRule ^fruits/([^/]*)/melons/([^/]*)$ goto/index.php?fruits=$1&melons=$3 [L]
RewriteCond %{QUERY_STRING} !berrys [NC]
RewriteRule ^fruits/([^/]*)/berrys/([^/]*)$ goto/index.php?fruits=$1&berrys=$3 [L] ....

标签: phpregex.htaccess

解决方案


推荐阅读