Search code examples
regexapache.htaccessurl-rewritingrule

Simple Rewrite rule with optional slash


i would simply add a rewrite rule in my htaccess to have this :

http://mysite/toto -> http://mysite/page.php?c=toto

and the same result for:

http://mysite/toto/ -> http://mysite/page.php?c=toto

my htaccess file:

Options +FollowSymlinks
RewriteEngine On
RewriteRule ^(.*)/?$  page.php?c=$1  [L]

It works with URL "http://mysite/toto"

but no with URL "http://mysite/toto/" --> result: http://mysite/page.php?c=toto/

How to fix this ?


Solution

  • OK, so you are running into a "greedy" match, the .* matches everything. What you can do is get every character that is not a / with this:

    ^([^/]).

    This says:

    1. Match start ^
    2. Match any character except / :[^/]
    3. Reference the step 2 match as $1 the parens do that

    This will do what you want. Note that if you have to escape the / character you will need to use /. I do not think you need to with htaccess files.