.htaccess - how to remove repeated words in url?

淺唱寂寞╮ 提交于 2020-01-02 14:13:05

问题


What is the regex in .htaccess to go from those urls:

example.com/hello-world-world
example.com/hello-world-hello

to this one:

example.com/hello-world

using RewriteCond like this:

RewriteCond %{REQUEST_METHOD}  !=POST
RewriteCond %{REQUEST_URI} ^REGEX$
RewriteRule . %1 [R=301,L]

回答1:


Removing all the duplicate words from slug is pretty tricky to be done in mod_rewrite only but here is a lookahead based regex rule than you can use:

RewriteEngine On

RewriteCond %{REQUEST_URI} ^/((?:[^-]*-)*)([^-]*)-((?=.*?\2).*)$
RewriteRule ^ /%1%3 [L,R]
  • This will redirect /hello-world-world to /hello-world
  • This will redirect /hello-world-hello to /world-hello

UPDATE: As per your comments:

RewriteCond %{REQUEST_METHOD} !=POST
RewriteCond %{REQUEST_URI} ^(/site/var1/var2)/((?:[^-]*-)*)([^-]*)-((?=.*?\3).*)$ [NC]
RewriteRule ^ %1/%2%4 [L,R]

This will redirect http://localhost/site/var1/var2/hello-world-world to http://localhost/site/var1/var2/hello-world this removing the duplicate.

UPDATE 2: As per your comments:

RewriteCond %{REQUEST_METHOD} !=POST
RewriteCond %{REQUEST_URI} ^(/site/var1/var2)/((?:[^/]*/)*)([^/]*)/((?=.*?\3).*)$ [NC]
RewriteRule ^ %1/%2%4 [L,R]

This will redirect http://localhost/site/var1/var2/hello/world/world/boy/boy to http://localhost/site/var1/var2/hello/world/boy




回答2:


According to your very good answer Anubhava here is my solution to rewrite the slug at the end of any url and not only based on /site/var1/var2

RewriteCond %{REQUEST_METHOD} !=POST
RewriteCond %{REQUEST_URI} ^(.*?)/((?:[^-]*-)*)([^-]*)-((?=.*?\3).*)$ [NC]
RewriteRule . %1/%2%4 [R=301,L]


来源:https://stackoverflow.com/questions/19433966/htaccess-how-to-remove-repeated-words-in-url

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