Forum Moderators: phranque
Hoping someone out there has done this before. I 'think' I'm on the right track, but haven't gotten the results I'm hoping for.
I have a hosting account (LAMP) that will always have one primary domain, but could also have several parked domains. Using .htaccess and mod_rewrite, for *any* domain, I want to add the 'www.' when it is not present.
The lower part of the process then re-directs everything to index.php in a subdir.
I think the problem lies in the RewriteRule - I don't think my syntax is correct. Also, I wonder if the domain matching pattern is a little overkill and I should just look for a 'www.' before any TLD?
Thanks in advance for any help with this,
D
----------------------------------
RewriteEngine On
RewriteBase /
# Redirect non-www to www
RewriteCond %{HTTP_HOST} ^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$
RewriteRule ^(.*)$/(.*)$ [$1...] [R=301,L]
# Redirect index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /subdir/index.php [L]
----------------------------------
# Redirect non-www to www
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} ^(([^.]+\.)[^.:]+)\.?(:[0-9]+)?$
RewriteRule ^(.*)$ http://www.%1/$1 [R=301,L]
You may also want to add another redirect rule to check for the FQDN and port numbers on requested "www" subdomains as well. Put this after the redirect above:
# Redirect FQDN to canonical domain and/or remove appended port numbers
RewriteCond %{HTTP_HOST} ^(([^.]+\.)[^.:]+)(\.¦\.?:[0-9]+)$
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
Jim
need to account for FQDN-foramt hostnames and also for the possibility that the hostname may have an appended port number
What you have worked. I only had to add the 'subdir' in the RewriteRules to make it work in the folder I have the app in.
For this to work in a sub-directory, I ended up with this:
RewriteEngine On
RewriteBase /
# Redirect non-www to www
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} ^(([^.]+\.)[^.:]+)\.?(:[0-9]+)?$
RewriteRule ^(.*)$ [%1...] [R=301,L]
# Redirect FQDN to canonical domain and/or remove appended port numbers
RewriteCond %{HTTP_HOST} ^(([^.]+\.)[^.:]+)(\.¦\.?:[0-9]+)$
RewriteRule ^(.*)$ [%1...] [R=301,L]
# Redirect index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /subdir/index.php [L]
Important: Replace the broken pipe "¦" character with a solid pipe character before use; Posting on this forum modifies the pipe character.
Thanks Jim!
Going extensionless and using a better pattern than "." would ensure that only extensionless URL requests would be rewritten.
At the same time you could lose the resource hungry -f check from your rule. You would probably still need the -d rule though.
It wouldn't need to make a file-system check when images, CSS, JS, SE account verification files (WMC/Analytics/etc), and so on, are requested.
Jim