I've been looking into mod_rewrite for my simple PHP CMS for a couple of days now and I found a rule that was supposed to work for me:

RewriteRule ^(\w+)/?$ view_post.php?url=$1

This is supposed to take www.example.com/example-post to the view_post.php page and query the post from a DB. This doesn't work if there are - (dashes) in the name. However, if I try www.example.com/examplepost, it will work as I can see the view_posts.php page loading and the SQL being constructed correctly, however no content loads because obviously, that won't match anything in the DB.

I could go a couple of ways around this, one would be to try to query the DB with both dashes and without, easily removed from the text with substr, however I would like for that rewrite rule to work with dashes as well for now. This is probably something related to the regexp, however it is beyond my comprehension.

Any help will be much appreciated!

2 Answers 2


You need to include the -(hyphen) in your rule match. Changing the line to:

RewriteRule ^([\w\-]+)/?$ view_post.php?url=$1

will work.


Obviously it does not work because - is not a word character.

You have to change the \w to . which matches any non-newline character.

By doing so pretty much all the URL paths except the homepage will be directed.

  • Ok so they will be redirected unless the document actually exists, so say I have an actual products.php page, will that be redirected as well if I change the rule as per your instruction?
    – TuxMeister
    Commented Jan 30, 2013 at 20:11
  • This change has the same effect as yours except that it will work for URLs with - in them. So, no, any path following the domain name will be redirected to view_post. Just like it was before. If you want to redirect only for requests that do not exist, then you need more complex rules that handle HTTP status codes.
    – Itai
    Commented Jan 30, 2013 at 20:21
  • OK so now I have this: RewriteRule ^(.+)/?$ view_post.php?url=$1. So now the GET parameter is not the page entered anymore, it's view_post.php, strange
    – TuxMeister
    Commented Jan 30, 2013 at 20:46
  • Your comment looks right, check that you typed it correctly in the .htaccess. Watch for missing spaces. Otherwise try prepending with a / as in RewriteRule ^/(.+)/?$ view_post.php?url=$1
    – Itai
    Commented Jan 30, 2013 at 20:53
  • @TuxMeister - Just to be clear about my first comment. A path will be redirected but not a file because of the terminating /. So, product.php will not but product.php/ will.
    – Itai
    Commented Jan 30, 2013 at 20:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.