使用.htaccess和Regex替换url路径的部分和查询字符串?

时间:2016-04-01 10:11:49

标签: regex .htaccess mod-rewrite

如何更换:

https://www.example.com/index.php?option=com_k2&view=item&id=7377

人:

https://www.portal-gestao.com/artigos/7377

我试过了:

RewriteRule ^index.php?option=com_k2&view=item&id=(.*)$ /artigos/$1 [R=301,L]

而且:

RewriteRule ^index.php?option=com_k2&view=item&id=\/([0-9]{4}-.*)$ /artigos/$1 [NC,R,L]

2 个答案:

答案 0 :(得分:0)

您无法在RewriteRule中捕获查询字符串。请改用RewriteCond。在.htaccess:

的顶部使用此规则
RewriteCond %{THE_REQUEST} /index\.php\?option=com_k2&view=item&id=([^\s&]+) [NC]
RewriteRule ^ https://www.portal-gestao.com/artigos/%1? [L,R=302]

答案 1 :(得分:0)

您也可以使用RewriteCond查询字符串匹配代码执行此操作:

# Individual explicit redirect rules based on exact matching URI|Query String parameters
# $1? Strip the option=com_k2&view=item&id=7377 Query String from the destination URI
RewriteCond %{QUERY_STRING} ^option=com_k2&view=item&id=7377$ [NC]
RewriteRule ^(.*)$ /artigos/7377/$1? [R=301,L]
RewriteCond %{QUERY_STRING} ^option=com_k2&view=item&id=7378$ [NC]
RewriteRule ^(.*)$ /artigos/7378/$1? [R=301,L]

# Dynamically redirect all matching Query Strings to equivalent URI
# %2 match and redirect to equivalent 4 digit number URI
# $1? Strip the option=com_k2&view=item&id= portion of the Query String from the destination URI
RewriteCond %{QUERY_STRING} ^(option=com_k2&view=item&id+)=([0-9]{4}+)$ [NC]
RewriteRule ^(.*)$ /artigos/%2/$1? [R=301,L]