Search code examples
.htaccessurlmod-rewrite

htaccess rewrite rule - clean up url


I'm looking at clearing up urls in my website which is built in PulseCMS.

Currently in blog posts the url includes the word blog, article number, and the title of the article and may look like this for a title of 'This, is a sample - Title' https://example.com/blog-10-this,-is-a-sample---title

I would like to

  1. put a '/' between the word blog and the title - make it go 'domain.com\blog\title'
  2. remove the blog number - so get rid of '-10', and
  3. remove the ',' and the extra '-' from the URL.

So ending up with the following https://example.com/blog/this-is-a-sample-title

My current htaccess rewrite rule is this, and I don't know where to start..


RewriteRule ^blog-page-([^-]*)$ ?page=$1&p=blog [L]
RewriteRule ^blog-([^-]*)+? ?d=$1&p=blog [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)$ index.php?p=$1 [L]

Any help is greatly appreciated!


Solution

  • Based on requirements and follow up comment, you can use these rules:

    RewriteEngine On
    
    # redirect from 
    # /blog-10-this,-is-a-sample---title
    # to /blog/10/this,-is-a-sample---title
    # executes repeatedly as long as there are multiple , or -- in URI
    RewriteRule ^(blog-\d+)[,-]+(.*?)(?:,|-{2,})(.*)$ $1-$2-$3 [N,DPI]
    
    # redirect to clean URL
    RewriteRule ^(blog)-(\d+)[,/-]+(.*) /$1/$2/$3 [L,R=302,NE,NC]
    
    # rewrite /blog/10/title
    RewriteRule ^blog[/-]([^-]+)/ ?d=$1&p=blog [L,QSA,NC]
    
    RewriteRule ^blog-page-([^-]*)$ ?page=$1&p=blog [L,QSA,NC]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteRule ^(.*)$ index.php?p=$1 [L,QSA]