Sunday, April 3, 2011

Simple mod_rewrite problem

I am new to using mod_rewrite and am trying to rewrite pages at the base level of my site:

www.site.com

I want to rewrite any of the following URLs www.site.com/main www.site.com/settings www.site.com/username

To: www.site.com/index.php?v=main www.site.com/index.php?v=settings www.site.com/index.php?v=username

I had this working when I had mod_rewrite set up under www.site.com/directory/ but can't figure out how to make it work with www.site.com

RewriteEngine On
RewriteRule ^/([^/\.]+)/?$ index.php?v=$1 [L]
From stackoverflow
  • You have an extra "/" there. That should be:

    RewriteEngine On
    RewriteRule ^([^/\.]+)/?$ index.php?v=$1 [L]
    
    Gumbo : You don’t have to escape the dot inside a character class declaration.
  • The correct rule would be...

    RewriteRule ^([^/\.]+)/?$ index.php?v=$1 [L,NC,QSA]
    

    But you might hit some problems - for example if you have REAL directories - this will rewrite them too and prevent you from using them. You have two options to avoid the problem, you can write many rules, like this:

    RewriteRule ^Directory/?$ index.php?v=directory [L,NC,QSA]
    

    Or you can use a "pretend directory" like this...

    RewriteRule ^Content/([^/\.]+)/?$ index.php?v=$1 [L,NC,QSA]
    

    In the second example, your URL would be www.site.com/Content/Directory/

    I've put NC and QSA on my attributes - No Case and Query String Append. You should definitely use NC, and QSA is useful in some implementations.

  • I would settle on whether the path should be /settings or /settings/ (you currently match both) and so on (personally, I prefer /settings.) I believe that it's a good idea to make paths as non-ambigous as possible. If you were to match paths like /settings, you would do like this:

    RewriteEngine On
    RewriteRule ^(\w+)$ index.php?v=$1 [L]
    

    Also have a look at the QSA flag if you want to support additional query parameters (for example: /settings?tab=password to index.php?v=settings&tab=password.) I'm mentioning it because that's something that bothered me in the beginning.

0 comments:

Post a Comment