pg.
pg.

Reputation: 2531

Rewrite htaccess so it doesn't need to repeat itself

I have one big htaccess file that does all the redirects for a site. Here is what I do for each directory:

RewriteRule ^CAKE_MIX/.php$  CAKE_MIX/index.php  [R,L]
RewriteRule ^CAKE_MIX$  CAKE_MIX/  [R,L]
RewriteRule CAKE_MIX/faqs.php$ /faqs/faqs.php?cat=CAKE_MIX [QSA]
RewriteRule CAKE_MIX/index.php$ /overview/overview.php?cat=CAKE_MIX [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /CAKE_MIX/*
RewriteRule . /faqs/faqs.php?cat=CAKE_MIX&question=%{REQUEST_URI}

RewriteRule ^COOKIE_DOUGH/.php$  COOKIE_DOUGH/index.php  [R,L]
RewriteRule ^COOKIE_DOUGH$  COOKIE_DOUGH/  [R,L]
RewriteRule COOKIE_DOUGH/faqs.php$ /faqs/faqs.php?cat=COOKIE_DOUGH [QSA]
RewriteRule COOKIE_DOUGH/index.php$ /overview/overview.php?cat=COOKIE_DOUGH [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /COOKIE_DOUGH/*
RewriteRule . /faqs/faqs.php?cat=COOKIE_DOUGH&question=%{REQUEST_URI}

And I do this for 18 different directories. How would I rewrite the htaccess to say something like "for any of the following directories: COOKIE_DOUGH, CAKE_MIX,ICE_CREAM, follow these rules?" and then the rules could be like:

RewriteRule ^DIRECTORY/.php$  DIRECTORY/index.php  [R,L]

And would only have to be written once? Is that possible?

Upvotes: 1

Views: 215

Answers (1)

anubhava
anubhava

Reputation: 785481

You can use regex alternation:

RewriteRule ^(CAKE_MIX|COOKIE_DOUGH|ICE_CREAM)/\.php$ $1/index.php  [R,L]

RewriteRule ^(CAKE_MIX|COOKIE_DOUGH|ICE_CREAM)$ $1/  [R,L]
RewriteRule (CAKE_MIX|COOKIE_DOUGH|ICE_CREAM)/faqs\.php$ /faqs/faqs.php?cat=$1 [QSA]
RewriteRule (CAKE_MIX|COOKIE_DOUGH|ICE_CREAM)/index\.php$ /overview/overview.php?cat=$1 [QSA,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /(CAKE_MIX|COOKIE_DOUGH|ICE_CREAM)/
RewriteRule . /faqs/faqs.php?cat=%1&question=%{REQUEST_URI}

Upvotes: 1

Related Questions