0

I have this code in my .htaccess to rewrite my URL from http://123domain.com to https://www.123domain.com but it's not working?

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

1 Answer 1

1

The internet is full of solutions for this. None of all those examples answered your question?

You cannot do both rewritings in a single step in a reliable manner. Instead you need two steps:

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [END,R=301]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [END,R=301]

Note: in case you are using a very old http server version you have to replace the END flags with L flags, should work the same in this case.


And a general hint: you should always prefer to place such rules inside the http servers host configuration instead of using dynamic configuration files (".htaccess"). Those files are notoriously error prone, hard to debug and they really slow down the server. They are only provided as a last option for situations where you do not have control over the host configuration (read: really cheap hosting service providers) or if you have an application that relies on writing its own rewrite rules (which is an obvious security nightmare).

Sign up to request clarification or add additional context in comments.

5 Comments

I appreciate all your comments on the issue, but for now the easiest way for me is to use .htaccess. I will dig into host configuration once I get it working this way. BTW: I tried your code but I am getting internal server error.
As suggested I had to use L instead of END
Sure, that means you are using a very old version of the apache http server. That will work fine, as long as you do not have interference with other rewriting rules.
Thanks. Is there a good resource somewhere about host configuration and how this is properly done? I want to learn.
First step certainly is the official documentation. It is of excellent quality as typical for OpenSource projects and comes with great examples. The http servers rewriting module is documented here: httpd.apache.org/docs/current/mod/mod_rewrite.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.