.htaccess mod_rewrite Simplify rules: Can I simplify multiple rules to one rule?

Viewed 17

Can I combine those two rules (with are working fine) into just one rule?

RewriteRule ^service/?$               service.php [NC]
RewriteRule ^service/([^/]+)/?$       service.php?id=$1 [NC]

Can I simplify those 4 rules into one?

RewriteRule ^hilfe/([^/]+)/([^/]+)/([^/]+)/?$        help/help.php?content=$1_$2_$3 [L,NC]
RewriteRule ^hilfe/([^/]+)/([^/]+)/?$                help/help.php?content=$1_$2 [L,NC]
RewriteRule ^hilfe/([^/]+)/?$                        help/help.php?content=$1 [L,NC]
RewriteRule ^hilfe/?$                                help/help.php [L,NC]

Thank you very much!

1 Answers

You could combine these rules into one, although whether that is a "simplification" or not is another matter - since the single rule is more complex.

For example,

RewriteRule ^service/?$               service.php [NC]
RewriteRule ^service/([^/]+)/?$       service.php?id=$1 [NC]

Could be represented as:

RewriteRule ^service/?(?:([^/]+)/?)?$ service.php?id=$1 [NC]

You basically need to make the additional parts to the URL optional and non-capturing (ie. (?:<regex>)?)

Note that the id parameter is always present and could therefore be empty.

RewriteRule ^hilfe/([^/]+)/([^/]+)/([^/]+)/?$        help/help.php?content=$1_$2_$3 [L,NC]
RewriteRule ^hilfe/([^/]+)/([^/]+)/?$                help/help.php?content=$1_$2 [L,NC]
RewriteRule ^hilfe/([^/]+)/?$                        help/help.php?content=$1 [L,NC]
RewriteRule ^hilfe/?$                                help/help.php [L,NC]

Could be represented as:

RewriteRule ^hilfe(?:/?([^/]+)(?:/?([^/]+)(?:/?([^/]+)/?)?)?)?$ help/help.php?content=$1_$2_$3 [L,NC]

The nesting of the parenthesised subpatterns makes this harder to read (maintain, debug, etc.)

The resulting content URL param will always have the 3 parts ($1, $2 and $3), except they could be empty, resulting in content=__, content=foo__, content=foo_bar_ etc.

Related