Redirecting HTTP to HTTPS correctly in Question2Answer script

485 Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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>
0
On

I use this:

DirectoryIndex index.php
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    RewriteCond %{REQUEST_URI} ^(.*)//(.*)$
    RewriteRule . %1/%2 [R=301,L]

    RewriteCond %{HTTPS} off
    RewriteCond %{HTTP:X-Forwarded-SSL} !on
    RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
    RewriteCond %{HTTP_HOST} ^www\.example\.com$
    RewriteRule ^(.*)$ "https\:\/\/example\.com\/$1" [R=301,L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^.*$ index.php?qa-rewrite=$0&%{QUERY_STRING} [L]
</IfModule>

If you don't like to redirect www, you can remove the line RewriteCond %{HTTP_HOST} ^www\.example\.com$ and the [OR] above