title: Combining Mod_rewrite Rules
body: <p>I have four urls I want to have rewritten.</p>
  
  <ol>
  <li>domain.com/index.php?id=1234 => domain.com/1234</li>
  <li>domain.com/a.php?id=1234 => domain.com/a/1234</li>
  <li>domain.com/b.php?id=4321 => domain.com/b/4321</li>
  <li>domain.com/gallery.php => domain.com/gallery</li>
  </ol>
  
  <p>Wherein, index checks a database and redirects to the correct page (a, b, c.php - ect), and if no valid ID is found, redirects to gallery.php.</p>
  
  <p>I can write the RewriteRule's that work for each case by themselves, but I don't know how to write it to handle all of them without the rules getting crossed.</p>
  
  <p>Here is my current Mod_rewrite .htaccess file :</p>
  
  <pre><code>RewriteEngine On
  
  RewriteCond %{REQUEST_URI} !/gallery$ #excludes case 4
  
  RewriteRule ^(.*)$ index.php?id=$1 #handles case 1
  
  RewriteRule ^(.*)/(.*)$ $1.php?id=$2 #handles cases 2 and 3
  
  RewriteCond %{REQUEST_URI} /gallery$
  RewriteRule ^/gallery$ /gallery.php [L] #handles case 4
  </code></pre>
  
  <p>This causes everything to redirect to domain.com/gallery.php and errors out attempting too many redirects. Even if I put in domain.com/a/1234, gets redirected to domain.com/a/gallery.php</p>
  
  <p>How do I go about separating these cases better - if it matches domain.com/1234 stop after case 1 - if it matches domain.com/a/1234 stop with case 2 and 3 - if it's for domain.com/gallery stop after domain.com/gallery.php is called...</p>
  
  <p>Thanks for the help all!</p>