Htaccess, mod_rewrite and regular expression for alphanumeric and dashes only

Just can't figure aout those regular expressions.

I have an .htaccess file with some url rewrites. Look below what I have now:

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

I don't think this is correct, I mean I think it could be better.

This is what they have to do.

  • If visitor visits or he shlould be redirected to
  • If visitor visits or he shlould be redirected to
  • The slugs only contain letters (A-Z and a-z), numbers (0-9) and dashes "-", so I need a correct regex for this

Can someone help me to build the correct rewrites?

13.10.2009 19:46:18

You can summarize your first two rules with this rule:

 RewriteRule (.+)/$ /$1 [L,R=301]

This will remove the trailing slash from requests. And your third rule looks fine. Expect that the range A-z will not just contain the ranges A-Z (0x41-0x5A) and a-z (0x61-0x7A) but also the character between those two ranges [, \, ], ^, = and `` . I would use[-A-Za-z0-9]` instead.

13.10.2009 19:48:32
I changed my htaccess with these two rules you supplied: RewriteRule (.+)/$ /$1 [L,R=301] and RewriteRule ^news/([-A-Za-z0-9]+)$ index.php?news=$1 [L] however when I go to, I get a 404 error..
Bundy 13.10.2009 20:01:04

this might work

RewriteRule ^/news(/)(.+)$ /index.php?news=$2 [L]
21.05.2010 23:10:09