问题
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