htaccess Example to Capture Directories

I thought i’d post an .htaccess example of regular expression good practice when trying to identify a directory structure, typically when you need to create a 301 rewrite rule.

In the above URL you want everything below the /category directory to be rewritten back to the /category directory.  Using category/(.*) which you would find posted on many sites is not optimal as .* is greedy it captures everything and has no control.  Ideally you want to be able to control the regular expression to capture each directory.

Directory capture

([^/]+) is the solution.  To break this down the regular expression is identifying the following:

[^/]  - anything that is not a /

[^/]+  - the plus sign means that anything but the / is looked for repeatedly until the / is discovered

([^/]+)  - the parenthesis captures the whole expression and can be referenced in the rewrite part of the rule.

category/([^/]+)/([^/]+)/([^/]+)/(.*) now captures each individual directory and filename ready to be used in the rewrite. You could  take this example one step further and capture all directories in one hit.

([^/]+)+ which means look for any character except / over and over again as detailed above but the external + means that once the / is found the whole process is repeated over and over again until there are no directories left.  So the opening part of the rule would look like category/([^/]+)+(.*)

Completing the htaccess example

As previously mentioned the ( ) sections of the htaccess example rule can be referenced in the rewrite.  So the first parenthesis is referenced by $1, the second by $2 and so on.

To rewrite the whole captured URL to remove all categories below /category the rule would look something like the following depending on whether you want to identify each directory or as a group:

RewriteRule ^category/([^/]+)/([^/]+)/([^/]+)/(.*)$  /category/$4 [R=301,L]
RewriteRule ^category/([^/]+)+(.*)$  /category/$2 [R=301,L]

Taking this one step further again if you need to create a rewrite rule for a directory name change at any level you can use a rule similar to this .htaccess example:

RewriteRule ^category/([^/]+)/([^/]+)/([^/]+)/(.*)$  /category/$1/$2/newlevel/$4 [R=301,L]

For more detailed information on all aspects of htaccess refer to the Apache website.

Posted in Configuration
Sign up for our newsletter!