Search code examples
regexmod-rewrite

Reduce path with valid regex in mod_rewrite


I need to have an unilateral function in mod_rewrite which giving a path produce a prefix using only a regex, unfortunately I have no control whatsoever on implementing this system.

I can only produce a regex and give it to the system administrator.

What I need is a regex pattern which is reducing a path in a two char prefix as follows

  1. case point: "abc.cde" -> "ac" (first char of first word and first char of second word)
  2. case minus: "abc-cde" -> "ac" (same as above)
  3. case point and minus after point: "abc.cde-fgh" -> "ac"
  4. case minus and point after minus: "abc-cde.fgh" -> "af"
  5. case no point and no minus: "random" -> "ra" (take first two char)

I saw that there is a tester on regrex for mod_rewrite here


Solution

  • You may use these rules in site root .htaccess:

    RewriteEngine On
    
    # skip all files and directories from rewrite rules below
    RewriteCond %{REQUEST_FILENAME} -d [OR]
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule ^ - [L]
    
    RewriteRule ^(\w)\w*[.-](\w)\w*/?$ /$1$2 [L,R=301]
    
    RewriteRule ^(\w)[\w-]*\.(\w) /$1$2 [L,R=301]
    
    RewriteRule ^(\w)(\w)[^.-]+$ /$1$2 [L,R=301]