.htaccess redirect rule for for removing article i

2019-08-27 21:09发布

问题:

I want to redirect the following URLs:

From: http://www.example.com/13-articlename
TO: http://www.example.com/articlename

And I have following code:

RewriteCond %{QUERY_STRING} id=13
RewriteRule (.*)$ http://www.example.com/articlename [R=301,L]

回答1:

In your rewrite you are expecting a querystring parameter of id however in your example it is actually part of the URL.

RewriteEngine on
RewriteBase /
RewriteRule (\d+)-([^/]*) $2 [R=301,L]
  • (\d+) = match any digits
  • - = a hyphen
  • ([^/]*) = any characters except a forward slash
  • $2 = redirect to the second matching group - ([^/]*)
  • [R=301] = use a HTTP 301 redirect (omit if you want to have it rewrite instead of redirect)
  • [L] = Last rule (don't process following rules)

You can test at http://htaccess.madewithlove.be/

input url
http://www.example.com/13-articlename

output url
http://www.example.com/articlename

debugging info
1 RewriteEngine on  
2 RewriteBase / 
3 RewriteRule (\d+)-([^/]*) $2 [R=301,L]
This rule was met, the new url is http://www.example.com/articlename 
Test are stopped, because of the R in your RewriteRule options. 
A redirect will be made with status code 301