Apache 2: Mod_Rewrite Help - If/else for directory exists

Posted by BHare on Server Fault See other posts from Server Fault or by BHare
Published on 2010-12-29T09:09:32Z Indexed on 2010/12/29 9:55 UTC
Read the original article Hit count: 307

Filed under:
|
|
|

This is my current and sloppy Apache 2 mod_rewrite. Keep in mine the part with site1 site2..etc has about 50 sites.

RewriteEngine   on        

RewriteCond     %{HTTP_HOST}                                 ^([^.]+)\.mainsite\.org$
RewriteCond     /home/%1/                                    -d
RewriteRule     ^(.+)                                        %{HTTP_HOST}$1
RewriteRule     ^([^.]+)\.mainsite\.org/media/(.*)           /home/$1/special/media/$2
RewriteRule     ^([^.]+)\.mainsite\.org/(.*)                 /home/$1/www/$2


RewriteCond     %{HTTP_HOST}                                ^mainsite\.org$   [NC]
RewriteRule     ^(.*)$                                      http://www.mainsite.org$1 [R=302]


RewriteCond     %{HTTP_HOST}            (site1|site2|site3|site4)\.(com|net|biz|org|us)$   [NC]
RewriteCond     %{REQUEST_URI}          !^/media/
RewriteRule     ^/(.*)$                  /home/%1/www/$1

RewriteCond     %{HTTP_HOST}            (site1|site2|site3|site4)\.(com|biz|net|org|us)$   [NC]
RewriteRule     ^/media/(.*)$          /home/%1/special/media/$1


RewriteCond     %{REQUEST_URI}          favicon.ico$
RewriteRule     ^(.*)$                  /misc/favicon.ico

So if someone tries to go to theirusername.mainsite.org it will check if /home/theirusername/ exists, and if it does use their www (/home/theirusername/www/) as the file location for web files. If they try they try to access theirusername.mainsite.org/media/ it will make a special file location to look for the file(s) at /home/theirusername/special/media/

I would like it if the username did NOT have /home/username that it would automatically default to www.mainsite.org. I am having a hard time understanding how to do skips and such. so:

If someone went to notrealusername.mainsite.org/forum/ it would auto direct to www.mainsite.org/forum/

Extra:

I am using repetitive code for other site for example lets say foobar has a website foobar.com, it goes through the same process as mainsite.org so figured maybe having something like:

RewriteCond %{HTTP_HOST} ^([^.]+).(mainsite.org|com|net|biz|org)$

where I could have one major rule for all existing domains who have a /home/

© Server Fault or respective owner

Related posts about apache

Related posts about apache2