'Replace part of a long URL and redirect

Is there a way to redirect the URL as follows:

URL is generated based on a filtering system so it is like this

https://example.com/product-category-no-slash-generated-part-is-autoadded-here

Due to the massive product number, it is impossible for me to change all generated URL-s but I need to change, for example, only no-slash part to something-else, so redirect does this:

  • Old URL:
    https://example.com/product-category-no-slash-generated-part-is-autoadded-here

  • New URL:
    https://example.com/product-category-something-else-generated-part-is-autoadded-here

I hope I managed to explain the problem.

I tried to use stuff like RewriteRule ^/no-slash/(.*)$ /something-else/$1 [L] but I think this does not work for what I need.



Solution 1:[1]

To replace no-slash with something-else in the URL-path that only consists of a single path-segment then you can do something like the following using mod-rewrite, near the top of the root .htaccess file.

RewriteEngine On

# Replace "no-slash" in URL-path with "something-else"
RewriteRule ^([\w-]+)no-slash([\w-]+)$ /$1something-else$2 [R=302,L]

This assumes the URL-path can only consist of the characters 0-9, a-z, A-Z, _ (underscore) and - (hyphen).

The $1 and $2 backreferences contain the matched URl-path before and after the string to replace repsectively.

I tried to use stuff like RewriteRule ^/no-slash/(.*)$ /something-else/$1 [L]

In this you are matching slashes in the URL-path - which do not occur in your example. You are also not allowing for anything before the string you want to replace (eg. product-catgeory-).

In a .htaccess context, the URL-path matched by the RewriteRule pattern does not start with a slash. S, a pattern like ^/no-slash will never match.


UPDATE:

another example. example.com/demo-tools-for-construction-work So word TOOLS in URL must be replaced with EQUIPMENT-AND-TOOLS.

(I'm assuming this should all be lowercase.)

A problem with your second example (in comments) is that tools also exists in the target URL, so this would naturally result in an endless redirect loop.

To prevent this "loop" you would need to exclude the URL you are redirecting to. eg. You could exclude URLs that already contain equipment-and-tools.

For example:

# Replace "tools" in URL-path with "equipment-and-tools"
# - except if it already contains "equipment-and-tools"
RewriteCond %{REQUEST_URI} !equipment-and-tools
RewriteRule ^([\w-]+)tools([\w-]+)$ /$1equipment-and-tools$2 [R=302,L]

The ! prefix on the CondPattern (2nd argument to the RewriteCond directive) negates the expression. So, in this case it is successful when equipment-and-tools is not contained in the requested URL.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1