Search code examples
apache.htaccessmod-rewritelaravel-4http-status-code-301

Laravel 4 htaccess Rewrite Rule with 301


I have following problem:

my website is available by two domains:

www.user.tucana.uberspace.de and www.my-domain.de

how is it possible to create a valid 301 Redirect from www.user.tucana.uberspace.de to www.my-domain.de ? I mean, if a user enter my webseite via www.user.tucana.uberspace.de/actual/news I want that my htaccess will redirect to www.my-domain.de/actual/news ...

In my htacces I create this code:

Options -MultiViews RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

RewriteBase /
RewriteCond %{HTTP_HOST} !=www.my-domain.de
RewriteRule (.*) http://www.my-domain.de/$1 [R=301,L]

but the problem is ... if an user enter the site at www.user.tucana.uberspace.de/actual/news he will be redirect to www.my-domain.de/index.php/actual/news

This code will work, but not for the root URL:

Options -MultiViews RewriteEngine On

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !=www.my-domain.de [NC]
RewriteRule ^ http://www.my-domain.de%{REQUEST_URI} [R=301,L,NE]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

If I use the code above, the URL www.user.tucana.uberspace.de/actual/news change to www.my-domain.de/actual/news - this is right, but if I type www.user.tucana.uberspace.de the URL will change to www.my-domain.de/index.php ... why :-( ? So, how can I avoid the index.php in the url?


Solution

  • You can keep your rules like this:

    Options -MultiViews
    
    RewriteEngine On
    
    # remove index.php
    RewriteCond %{THE_REQUEST} /index\.php [NC]
    RewriteRule ^(.*?)index\.php$ /$1 [L,R=302,NC,NE]
    
    RewriteCond %{HTTPS} off
    RewriteCond %{HTTP_HOST} !^www\.my-domain\.de$ [NC]
    RewriteRule ^ http://www.my-domain.de%{REQUEST_URI} [R=301,L,NE]
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
    

    Also test it out in a new browser to avoid 301 caching.