更新时间:2023-02-21 13:46:06
我认为随机"是指打算是任何随机单词(小写字母仅a-z)?而那个"32-11"也是可变的吗?
在这种情况下,请在 .htaccess
文件的顶部中尝试以下操作:
RewriteEngine开启RewriteRule ^(this-is-static/[a-z] +)_([^/] +)$/$ 1/$ 2 [R = 302,L]
$ 1
后向引用与URL路径的第一部分匹配,直到并包括"random"(随机)字符.字(不包括第一个下划线). $ 2
后向引用将第一个下划线后的所有 匹配到URL路径的末尾.
通过在第二个反向引用中排除斜杠,它自然无法匹配您不希望重定向的URL,因为它包含更多路径段.
更新:在"this-is-static"之后,我遇到了一个带有连字符的URL的小问题....使用上面的示例,如果单词"random"是是随机文本"它不会重定向...尝试编辑以上内容均无济于事
您只需要在 [a-z]
字符类的末尾添加连字符,即. [az-]
(第一个连字符代表范围 a
至 z
).换句话说:
RewriteRule ^(this-is-static/[a-z-] +)_([^/] +)$/$ 1/$ 2 [R = 302,L]
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
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]