Redirect using Htaccess- URL has underscore and change it to a slash

僤鯓⒐⒋嵵緔 提交于 2021-01-28 11:47:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!