Joel Hackney
Joel Hackney

Reputation: 147

Combining Mod_rewrite Rules

I have four urls I want to have rewritten.

  1. domain.com/index.php?id=1234 => domain.com/1234
  2. domain.com/a.php?id=1234 => domain.com/a/1234
  3. domain.com/b.php?id=4321 => domain.com/b/4321
  4. domain.com/gallery.php => domain.com/gallery

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.

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.

Here is my current Mod_rewrite .htaccess file :

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

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

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...

Thanks for the help all!

Upvotes: 1

Views: 108

Answers (1)

anubhava
anubhava

Reputation: 785276

Replace your code with this:

RewriteRule ^gallery/?$ /gallery.php [L,NC] #handles case 4

RewriteRule ^([^/]+)/([^/]+)/?$ /$1.php?id=$2 [L,QSA] #handles cases 2 and 3

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ /index.php?id=$1 [L,QSA] #handles case 1

Upvotes: 1

Related Questions