Htaccess, mod_rewrite and regex for alphanumeric and dash
I just can't figure out these regexes.
I have a .htaccess file with some url rewrites. Take a 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 it could be better.
This is what they have to do.
- If a visitor visits www.mydomain.com/news or www.mydomain.com/news/ it should be redirected to www.mydomain.com/index.php
- If a visitor visits www.mydomain.com/news/test-slug or www.mydomain.com/news/test-slug/ it should be redirected to www.mydomain.com/index.php?news=test-slug
- The bullets only contain letters (AZ and az), numbers (0-9) and dash "-", so I need a correct regex for this
Can anyone help me build the correct rewrites?
source to share
You can summarize your first two rules using this rule:
RewriteRule (.+)/$ /$1 [L,R=301]
This will remove the trailing slash from the requests. And your third rule looks great. Expect range A
- z
will not contain ranges A
- z
(0x41-0x5A) and A
- z
(0x61-0x7A), but also the character between these two ranges [
, \
, ]
, ^
, =
and `` . I would use
[- A-Za-z0-9] `instead.
source to share