Search code examples
wordpress.htaccesshttp-redirectmod-rewrite

Redirect ALL Urls ending with a word to its same URL without that ending word


How to redirect ALL URLs via .htaccess so that ALL urls ending with -text/ are redirected to (url)/, removing the -text part.

For example, ALL urls ( with word -text/ ) :

https://www.example.com/example-text/

to

https://www.example.com/example/

Solution

  • To remove -text at the end of the URL-path (before the final slash) you could do something like the following at the top of your root .htaccess file (before the # BEGIN WordPress section).

    For example:

    RewriteRule (.+)-text/$ /$1/ [R=302,L]
    

    No other directives are required (since the RewriteEngine On directive is in the WordPress code block that follows).

    The $1 backreference (in the substitution string) contains the URL-path that precedes -text/ at the end of the URL-path.

    This applies to any URL that ends in -text/. If it should only apply to URLs that contain a single URL-path segment (as in your example), then you can modify the RewriteRule pattern as follows:

    RewriteRule ^([^/]+)-text/$ /$1/ [R=302,L]
    

    This will match /example-text/ (single path segment) as before, but not /foo/bar-text (two path segments).

    Note that these are 302 (temporary) redirects. If this is intended to be permanent then change it to a 301, but only once you have tested that it works as intended. 301s are cached persistently by the browser by default so can make testing problematic.