如何写一个Apache重写规则redirect请求到一个目录到SSL?

我正在尝试将服务器上的目录中的所有请求redirect到https。 我已经在一个单独的configuration(在config.d目录内)和.htaccess文件中尝试了以下内容。 既不工作,也不会造成错误。

<IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] </IfModule> 

当我尝试在一个configuration文件上面是在一个块内。

编辑
这是我在configuration文件中的代码:

 <Directory "/var/www/html/ssl_dir/"> Options Indexes MultiViews FollowSymLinks AllowOverride All <RequireAny> Require ip xx.xx.xx.0/24 Require ip ::1 </RequireAny> <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] </IfModule> </Directory> 

差不多了!

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

https://stackoverflow.com/questions/3307025/force-https-on-certain-urls-and-force-http-for-all-others

我的第一个回答错误地使用了SERVER_NAME,它不一定等于HTTP_HOST。 服务器名称可以与用于访问它的域名完全不同。