如何重定向到特定的URL

I would like to redirect if user open with

1 http://example.com to https://www.example.com

2 http://www.example.com to https://www.example.com

3 http://example.com/user/(anystring) to https://www.example.com/user/(anystring)

4 http://www.example.com/user/(anystring) to https://www.example.com/user/(anystring)

I've tried this htaccess

RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule ^/?$ "https\:\/\/www\.example\.com\/" [R=301,L]

RewriteCond %{HTTP_HOST} ^example\.com\/user\/*$ [OR] 
RewriteCond %{HTTP_HOST} ^www\.example\.com\/user\/*$
RewriteRule ^/?$ "https\:\/\/www\.example\.com\/user\/$1" [R=301,L]

3rd and 4th is not working properly, (anystring) is not accessible, I'm going to set COOKIE, but its not available after redirection.

I think you can simplify this to a single rule:

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

And the test for the host name is actually only required if you have other virtual hosts based in the same rule set that you do not want to rewrite.


And a general hint: you should always prefer to place such rules inside the http servers host configuration instead of using .htaccess style files. 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).