Welcome Guest, Not a member yet? Register   Sign In
htaccess to hide index.php AND force www.mydomain.com
#1

[eluser]Unknown[/eluser]
Hi, Everyone,

I was able to successfully hide index.php using htaccess and mod_rewrite. However, I recently discovered that my site fails if users omit the www in the domain name (i.e., if they enter mydomain.com instead of www.mydomain.com). I have been able to force the www, but then the hiding of index.php fails.

I'd like to combine these two solutions so that the index.php file is hidden AND www is always prepended when the user omits it.

Here is the code I use in my htaccess file for hiding the index.php file:
Code:
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt|css|javascript)
RewriteRule ^(.*)$ /index.php/$1 [L]

Here is the code I use in my htaccess file for forcing the www:
Code:
RewriteCond %{HTTP_HOST} !^www\.mydomain\.com$ [NC]
RewriteRule .? http://www.mydomain.com%{REQUEST_URI} [R,L]


In the end, the following should happen:

* mydomain.com/aaa/bbb/x/ should become www.mydomain.com/aaa/bbb/x/
* mydomain.com/aaa/ should become www.mydomain.com/aaa/

I list these because this is where I am seeing problems. The first case fails by removing /aaa/. The second case fails because it inserts index.php.


Can someone show my how to combine these rules so that both conditions rewrite correctly?

Thanks in advance,
Ed
#2

[eluser]bretticus[/eluser]
This configuration works for me. I look for the absence of www before letting the rules below process. Notice the [R=301...] flag to tell the browser to redirect followed by the L flag to tell apache to stop processing the URL. In other words, if the redirect rule matches, then the rules below it are not ran (until the redirect happens and the very next page does not match the www rule.)

Also note that the conditions to avoid real files and directories is much easier to maintain than the condition with the exclusion list. I also use a system folder exclusion rule for added security (optional.)


Quote:RewriteCond %{HTTP_HOST} ^mydomain\.com$ [NC]
RewriteRule ^/(.*)$ http://www.mydomain.com/$1 [R=301,L]

RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?/$1 [L]




Theme © iAndrew 2016 - Forum software by © MyBB