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

Time:10-02

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/

CodePudding user response:

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.

CodePudding user response:

  • This is not exactly your answer

  • But I put this answer here so that maybe it will solve the problem of some other people

    function forward_to_url(){
     $self = $_SERVER["REQUEST_URI"];
    
     //The string you want to find
     $itemCheck = "url";
     $needle = $itemCheck. '/';
    
     //Any Address You want redirect
     $forwardlink = '/'.preg_replace('/'.strtolower($itemCheck).'/','',strtolower($self));
    
     $length = strlen($needle);
     $urlend= substr($self, -$length);
    
     if ($urlend == $needle or $urlend == $itemCheck) {
         wp_redirect($forwardlink, 301);
     }
    }
    add_action('template_redirect', 'forward_to_url');
    
  • Related