void
void

Reputation: 405

Incorrect redirection from .htaccess

I want to redirect all non-www and all non-https to https://www URL.

I have a .htaccess containing the following code:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI}$1 [R=301,L]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}$1

That is working for the root path:

OK https://www.mywebsite.com => https://www.mywebsite.com
OK http://mywebsite.com => https://www.mywebsite.com
OK https://mywebsite.com => https://www.mywebsite.com
OK http://www.mywebsite.com => https://www.mywebsite.com

But there is (kind of) a bug when I try to go in sub-folder:

OK https://www.mywebsite.com/tmp => https://www.mywebsite.com/tmp
KO https://mywebsite.com/tmp => https://www.mywebsite.com/tmp/tmp
KO http://www.mywebsite.com/tmp => https://www.mywebsite.com/tmp/tmp
KO http://mywebsite.com/tmp => https://www.mywebsite.com/tmp/tmp

As you can see, the sub-folder is appended once again and it gives a 404 Error.

How could I fix my .htaccess rules to get the expected redirections ?

Thank you very much

Upvotes: 2

Views: 34

Answers (1)

anubhava
anubhava

Reputation: 785196

Problem is use of %{REQUEST_URI}$1 which is adding captured value i.e. URI at the end of REQUEST_URI.

Also as an optimization you can combine both rules into one like this:

RewriteEngine On

RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]

Make sure to clear your browser cache before testing this change.

Upvotes: 4

Related Questions