Chris
Chris

Reputation: 4728

RewriteRule to match anything alphanumeric or dash only

I am trying to write a rule that matches domain.com/abc

RewriteRule ^([^/\.]+)?$ results.php?category=$1 [L,NC]

This works and category=abc but this rule also seems to be triggered if I just go to domain.com

I need my rule to only match if the URL after the slash contains alphanumeric characters or a dash. It can not match a forward slash as domain.com/abc/123 would not be valid.

domain.com/abc123 is good
domain.com/abc-123 is good
domain.com/abc/123 should not match
domain.com should not match
domain.com/ should not match

Upvotes: 1

Views: 1841

Answers (1)

anubhava
anubhava

Reputation: 785156

You can use:

RewriteRule ^([\w-]+)/?$ results.php?category=$1 [L,QSA]

\w matches [a-zA-Z0-9_]

To avoid matching underscore use:

RewriteRule ^([a-zA-Z0-9-]+)/?$ results.php?category=$1 [L,QSA]

To safeguard it use this condition to avoid matching directories:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w-]+)/?$ results.php?category=$1 [L,QSA]

Upvotes: 4

Related Questions