user1748794
user1748794

Reputation: 57

Htaccess rewrite not liking dashes

I use the following rewrite rule to behind the scenes rewrite addresses such as /pageName and /pageName/ to index.php?page=pageName. It works perfectly except when the pageName contains a -.

RewriteEngine On
RewriteRule ^(\w+)$ /index.php?page=$1
RewriteRule ^(\w+)/$ /index.php?page=$1

How can I get these rewrite rules to accept any input (or at least input containing A-Z, 1-9, and -'s.

Thank you.

Upvotes: 1

Views: 67

Answers (3)

jeroen
jeroen

Reputation: 91734

You (probably...) do not want to rewrite any existing files, so you could use something like:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([\w\-]+)/?$ /index.php?page=$1

Note that I made the trailing slash optional.

Upvotes: 1

Marc B
Marc B

Reputation: 360662

\w is the equivalent of [0-9a-zA-Z_]. e.g. upper+lower case alphabetical characters, and the undercore. - is NOT part of it, so you'll have to explicitly allow it:

^([\w\-])$

by creating your own character class.

Upvotes: 1

Lars Ebert-Harlaar
Lars Ebert-Harlaar

Reputation: 3537

RewriteEngine On
RewriteRule ^([0-9a-zA-Z-]+)$ /index.php?page=$1
RewriteRule ^([0-9a-zA-Z-]+)/$ /index.php?page=$1

This should work.

Upvotes: 1

Related Questions