Search code examples
apache.htaccesscodeignitermod-rewrite

htaccess redirects to https with index.php


Hey i'm using codeigniter and added rewrite rules to remove the index.php from the url which works fine.

However, i've added a rule to redirect all http requests to https but when it does it redirects with the index.php.

Meaning if i enter this url : domain.com/somecoolcontroler

It will redirect me to : https://domain.com/index.php/somecoolcontroler

But when navigating afterwards it comes back to normal urls without it so i guess the problem is in the redirect rule, this is what i put in htaccess :

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L] 
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

How can i fix that?


Solution

  • You need to put your redirect rules before your routing rules. The rewrite engine loops so even if you have the L flag, it'll loop past your routing rules the second time around and hit the redirect rule, except this time, the URI has been rewritten already.

    If the rewrite rule is first, it'll redirect the browser before the routing rule gets applied. Then, when the redirected request is made, the routing rule gets applied. You'd also need a L flag.

    RewriteEngine On
    
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule .* index.php/$0 [PT,L]