Search code examples
apache.htaccessmod-rewritehttp-redirecthttp-status-code-301

Htaccess Redirect Wildcard


We have recently transferred our site to a new CMS and I am stuck on redirecting one directory.

Our old URL structure was this:

/directory/sub-directory/this-is-the-post/81281/

I want to redirect it to:

/this-is-the-post-81281

Current .htaccess file

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

RewriteEngine On
RewriteRule ^[^/]+/[^/]+/([^/]+)/([0-9]+)/?$ /$1-$2 [L,R]

#Redirected wildcard /new to forward slash.
 RedirectMatch 301 /new/(.*) /$1

Solution

  • Put this code in your DOCUMENT_ROOT/.htaccess file:

    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    
    RewriteRule ^[^/]+/[^/]+/([^/]+)/([0-9]+)/?$ /$1-$2 [L,R]
    
    RewriteRule ^new/(.*)$ /$1 [L,R]
    
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
    </IfModule>