Replace portions of a url path and query string using .htaccess and Regex?

我们两清 提交于 2019-12-17 22:01:03

问题


How do I replace :

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

By:

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

I tried this :

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

And this:

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

回答1:


You cannot capture query string in RewriteRule. Use a RewriteCond instead. Use this rule at top of your .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]



回答2:


You can also do this with RewriteCond Query String matching code:

# 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]


来源:https://stackoverflow.com/questions/36353625/replace-portions-of-a-url-path-and-query-string-using-htaccess-and-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!