问题
I've gone through a couple dozen answers but none seem to give me what I need, hopefully, someone can help me out here...
My URL structure looks like this
https://www.example.com/this-is-static/random_text_32-11
and I need to redirect to
https://www.example.com/this-is-static/random/text_32-11
So it's always the underscore right after "random" that needs to redirect to a slash /
Everything after the underscore is dynamic (random_text_32-11
)
There are other URLs that look like the below and I wouldn't want those affected by this piece of code
https://www.example.com/this-is-static/random-words/morerandom/words-change_5-911
回答1:
I assume that "random" is intended to be any random word (lowercase letters only a-z)? And that "32-11" is also variable?
In which case, try something like the following at the top of your .htaccess
file:
RewriteEngine On
RewriteRule ^(this-is-static/[a-z]+)_([^/]+)$ /$1/$2 [R=302,L]
The $1
backreference matches the first part of the URL-path up to and including the "random" word (excluding the first underscore). The $2
backreference matches everything after the first underscore, excluding any slashes, to the end of the URL-path.
By excluding slashes in the second backreference it naturally fails to match the URL that you don't want to be redirected, since this contains more path segments.
UPDATE: I ran into a slight snag with URLS containing a hyphen right after "this-is-static" ... using the above example, if the word "random" was "random-text" it wont redirect... tried editing the above to no avail
You would just need to add a hyphen to the end of the [a-z]
character class, ie. [a-z-]
(the first hyphen represents a range a
to z
). In other words:
RewriteRule ^(this-is-static/[a-z-]+)_([^/]+)$ /$1/$2 [R=302,L]
来源:https://stackoverflow.com/questions/62970093/redirect-using-htaccess-url-has-underscore-and-change-it-to-a-slash