Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

.htaccess - HTACCESS : RegEx match replace for URL

I want the htaccess Redirect 301 to do the following using regex:

http://example.com/folder/abc_123_123.htm

to

http://example.com/abc-123-123.shtml

The 3 objectives of new URL are

  • delete /folder/

  • replace all _ with -

  • replace htm with shtml

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Best I'm aware, your point #2 cannot be done without a RewriteMap, which requires some pesky configuration, or multiple rules.

This implementation should be generic and work for any number of underscores, but it's expensive in that it might trigger many redirect (in fact, potentially enough to fire redirect errors in browsers if you've tons of underscores in your paths):

RewriteBase /
RewriteRule ^(folder/[^_]*)_(.*.html?)$ /$1-$2 [L,R=301]
RewriteRule ^folder/(*+).html?$ /$1.shtml [L,R=301]

Alternatives include enumerating use-cases as needed, or (better, I suspect) rewriting the request to a perl or php script and doing the regexp_replace + redirect 301 from there.

RewriteBase /
RewriteRule ^folder/(*+).html?$ /folder/redirect.php [L,QSA]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...