apache.htaccessmod-rewritehttp-redirectquestion2answer

Redirecting HTTP to HTTPS correctly in Question2Answer script


I have searched for this question for many days and tried so many different methods but nothing works so far. I am using the Question2Answer script and I want to redirect all the HTTP requests to HTTPS.

My URL structure is set to :

/123/why-do-birds-sing (requires htaccess file)

and the htaccess file is as follow:

DirectoryIndex index.php
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} ^(.*)//(.*)$
RewriteRule . %1/%2 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ index.php?qa-rewrite=$0&%{QUERY_STRING} [L]
RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"'
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]
</IfModule>

This correctly redirects http://example.com to https://example.com. However, if the user enters an address like this : www.example.com/users they are redirected to https://example.com/index.php?qa-rewrite=users which returns a 404 error.

The index.php?qa-rewrite= is added automatically and removing it from the htaccess totally messes up everything and I think it should be there.


Solution

  • This is because you need all of your redirect rules before any of the routing rules (the ones without the R flag), so:

    DirectoryIndex index.php
    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_URI} ^(.*)//(.*)$
    RewriteRule . %1/%2 [R=301,L]
    RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"'
    RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^.*$ index.php?qa-rewrite=$0&%{QUERY_STRING} [L]
    </IfModule>