1

For whatever reason I can’t seem to get this right. I’ve looked at many examples on here and on the Apache website. I’m trying to force www.example.com instead of example.com on both HTTP and HTTPS, but I am not trying to force use of HTTPS instead of HTTP.

The following code seems to work for all HTTPS connections, but will not cause a redirect for HTTP connections.

RewriteEngine On
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301]

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule ^ http://www.example.com%{REQUEST_URI} [R=301]

2 Answers 2

1

Your solution seems right. But let me provide some checkpoints you can perform.

  • Are HTTP and HTTPS set to point to the same physical directory?
  • Have you tried asking on server fault?
  • Can you try using modifiers to check like

Code:

RewriteEngine On
RewriteCond %{HTTPS} = on
RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]

RewriteCond %{HTTPS} != on
RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule ^ http://www.example.com%{REQUEST_URI} [R=301,L]
3
  • Yes they use the same file directory. I have not asked on server fault. I tried using the code you posted and got a 500 internal server error. Commented Dec 2, 2010 at 14:22
  • @Brian Perin: The StackExchange markup was messed up (I guess there's a bug in it when you try to follow a list directly with a code block). The RewriteCond s needed to be on separate lines. Commented Jan 31, 2011 at 17:22
  • "got a 500 internal server error" - the 500 error is caused by the incorrectly formatted CondPatterns: There should be no space after = in = on and != on. It should be =on and !=on respectively. (Or omit the = altogether; it's not strictly required.)
    – MrWhite
    Commented Jan 3, 2019 at 1:35
1

I've had the same problem, and the below solved it for me.

RewriteEngine On
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
1
  • The first condition (that checks that the Host header is not empty) is not necessary, since the second condition checks that the Host header is a specific value. If the second condition is successful then the first condition must also be successful.
    – MrWhite
    Commented Jan 3, 2019 at 1:41

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.