Adding a rule to the htaccess subdomain rewrite

.htaccessapache-2.2mod-rewrite

I recently had some help from icyrock.com with a htaccess rewrite that sends all subdomain requests to domain.com/apps

You can find the thread here and the code is here:

RewriteBase /
RewriteEngine On

#### URL Rewrite Handler for Subdomains (by Randall Krause) ####

RewriteCond %{ENV:REDIRECT_SUBDOMAIN} =""
RewriteCond %{HTTP_HOST} ^([a-z0-9][-a-z0-9]+)\.domain\.com\.?(:80)?$ [NC]
RewriteCond %{DOCUMENT_ROOT}/apps/%1 -d
RewriteRule ^(.*) apps/%1/$1 [E=SUBDOMAIN:%1,L]
RewriteRule ^ - [E=SUBDOMAIN:%{ENV:REDIRECT_SUBDOMAIN},L]

As I said this works really well, but I need to add two more rules that I am having trouble integrating without conflicting with the above code.

  1. For any requests that are NOT for subdomains I need the main website URL (http://domain.com) to rewrite to http: // www.domain.com
  2. For any requests that are NOT for the subdomains I also need to rewrite the URLS to remove an index.php from the URL.

The code for this is:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

Adding this in its current form BEFORE the subdomain rewrite rule breaks it.

The only solution I have found is to explicitly define which files are not to be covered by the above rule by doing something like this:

RewriteCond $1 !^(index\.php|images|robots\.txt)

Does anyone have any ideas?

Thanks,

Tim

Best Answer

Haven't tested it, but try something along these lines (you might need to tweak it):

RewriteCond %{HTTP_HOST} ^domain\.com(:80)?$ [NC]
RewriteRule ^(.*)(?:index.php)?$ http://www.domain.com/$1 [R=permanent,L]

Put the code after RewriteEngine On (i.e. before your first RewriteCond). Note that it's going to remove all index.php endings (i.e. domain.com/a/b/c/index.php will become www.domain.com/a/b/c/. Taken from here:

I suggest you do some reading on mod_rewrite, such as:

if you are going to need it every second day - pays off... :)

Related Topic