Sam Leurs
Sam Leurs

Reputation: 490

RewriteCond for multiple RewriteRules

currently, I have the following .htaccess-file.

RewriteEngine on

RewriteCond %{HTTP_HOST} ^([a-z-]+)\.example\.com$ [NC]
RewriteCond %1 !^(javascript|css|images)$ [NC]
RewriteRule ^ index.php?file=index [NC,L,QSA]

RewriteCond %{HTTP_HOST} ^([a-z-]+)\.example\.com$ [NC]
RewriteCond %1 !^(javascript|css|images)$ [NC]
RewriteRule ^language/?$ index.php?file=language [NC,L,QSA]

RewriteCond %{HTTP_HOST} ^([a-z-]+)\.example\.com$ [NC]
RewriteCond %1 !^(javascript|css|images)$ [NC]
RewriteRule ^about-us/?$ index.php?file=about_us [NC,L,QSA]

As you can see, I have to copy the following 2 lines for every RewriteRule:

RewriteCond %{HTTP_HOST} ^([a-z-]+)\.example\.com$ [NC]
RewriteCond %1 !^(javascript|css|images)$ [NC]

This works, but I want to know if there is a better solution?

What I want?

For example, when a user visits http://{subdomain-here}.example.com/about-us, the page index.php?file=about_us must show up. For every subdomain, except for the subdomains javascript, css and images.

Edit 1: If a visitors goes to http://javascript.example.com/about-us, the browser should give a 404 error.

Edit 2: a "general" regex (e.g. (.*)) will not work because the name of the file in the URL is not always the same as the original filename. http://subdomain.example.com/about-us should point to index.php?file=about_us (see the _) and not to index.php?file=about-us.

Upvotes: 1

Views: 38

Answers (2)

Justin Iurman
Justin Iurman

Reputation: 19026

You can apply the opposite logic

RewriteEngine on

# Don't touch anything when it comes to those 3 subdomains
RewriteCond %{HTTP_HOST} ^(?:javascript|css|images)\.example\.com$ [NC]
RewriteRule ^ - [L]

# If we reach this part, this means we're not in the 3 subdomains restriction

RewriteRule ^$ /index.php?file=index [NC,L]
RewriteRule ^language$ /index.php?file=language [NC,L]
RewriteRule ^about-us$ /index.php?file=about_us [NC,L]

You can see that as an equivalent to

if subdomain in (javascript, css, images)
  return

do something here for other subdomains

Upvotes: 1

Amit Verma
Amit Verma

Reputation: 41249

You can use this

RewriteEngine on

RewriteCond %{HTTP_HOST} ^([a-z-]+)\.example\.com$ [NC]
RewriteCond %1 !^(javascript|css|images)$ [NC]
RewriteRule ^(.*) index.php?file=$1 [NC,L,QSA]

or the following :

RewriteEngine on

RewriteCond %{HTTP_HOST} !^(javascript|css|images) [NC]
RewriteRule ^(.*) index.php?file=$1 [NC,L,QSA]

Upvotes: 0

Related Questions