Andre
Andre

Reputation: 673

apache rewrite rule: http to www doesn't work

I tried to define a apache rewrite-rule to redirect users which type http://mydomain.net to get on my website to www.mydomain.net. So in the .htaccess-file I wrote the following:

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

But this doesn't work: when I type mydomain.net I get in my browser

Forbidden

You don't have permission to access / on this server.

When I try the opposite

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

that works (when I type in www.mydomain.net I get to mydomain.net). Does anybody know why and how to solve the problem?

Here is my .htaccess:

RewriteEngine On

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

RewriteRule ^typo3$ - [L]
RewriteRule ^typo3/.*$ - [L]
RewriteRule ^uploads/.*$ - [L]
RewriteRule ^fileadmin/.*$ - [L]
RewriteRule ^typo3conf/.*$ - [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
# naechste Zeile auskommentieren,
# wenn .html Endung in RealURL eingestellt ist
RewriteRule (.*[^/])$ http://%{HTTP_HOST}/$1/ [L,R]

RewriteCond %{REQUEST_FILENAME}/index.html -f
RewriteRule / %{REQUEST_URI}/index.html [L]

RewriteCond %{REQUEST_FILENAME}/index.htm -f
RewriteRule / %{REQUEST_URI}/index.htm [L]

RewriteCond %{REQUEST_FILENAME}/index.php -f
RewriteRule / %{REQUEST_URI}/index.php [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule .* /index.php

Upvotes: 1

Views: 510

Answers (2)

codenathan
codenathan

Reputation: 774

             RewriteEngine on
             RewriteCond %{HTTP_HOST} !^www\. [NC]
             RewriteCond %{HTTP_HOST} !\.([a-z-]+\.[a-z]{2,6})$ [NC]
             RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Use the above code it should work and to fix the forbidden error bit you will need to add in the following bit of code in apache httpd.conf file :-

            <Directory />
            Require all granted
            </Directory>

You can find more permission about the 403 error on an article I have written here : - http://codenathan.com/apache/you-dont-have-permission-to-access-the-requested-directory

Upvotes: 0

Panama Jack
Panama Jack

Reputation: 24448

You should try it this way. You need a forward slash before $1. However I would do it this way so that it won't affect subdomains. Change the condition to check for the TLD instead of the absence of www.

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

Upvotes: 2

Related Questions