Search code examples
regexapache.htaccessmod-rewriteapache2

How to add + (plus) to regex in Apache RewriteRule?


I currently have the following in my .htaccess file, which rewrites A-Z, 1-9, a-z, and - inputs to a PHP file:

RewriteRule ^([A-Z­a-z­0-9­-]+)/?$ index.php?url=$1 [L]

I need to add + to the regex. How can I do this?

I've tried:

RewriteRule ^([A-Z­a-z­0-9­-+]+)/?$ index.php?url=$1 [L]

I've also looked at several regex cheat sheets, which really are not useful.


Solution

  • At face value the regex you've posted is "OK" and should work (although you should consider backslash-escaping the last hyphen in the character class, or moving this to the last character in the character class, in order to avoid any future ambiguity with it being interpreted as a range indicator). The + can be used unescaped in the character class as it carries no special meaning here.

    For example (copy/paste the following):

    RewriteRule ^([A-Za-z0-9+-]+)/?$ index.php?url=$1 [L]
    

    (This has had the erroneous characters removed - see below.)

    Alternatively, if you are OK with matching an underscore (_) as well then you could use the \w (word chars) shorthand character class to simplify it a bit: ^([\w+-]+)/?$

    HOWEVER, you have a soft-hyphen (U+00AD) - invisible to the naked eye - embedded between each range in the character class, which could be breaking the regex. For example, expanding the hidden unicode characters, this is the actual (invalid) regex you are trying to use:

    ^([A-ZU+00ADa-zU+00AD0-9U+00AD-+]+)/?$