我有以下内容:
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} protected [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [L,R=301]
RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} !protected [NC]
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [L,R=301]
如果该目录被称为“ protected ”,请确保用户使用的是 https。如果目录不是“ protected ”,请确保用户使用的是 http。
这很好用,但我如何指定额外的目录?
此外,有没有一种方法可以在不必指定目录两次的情况下完成?一次包含它,一次排除它?
谢谢!
更新
虽然我的“ protected ”文件夹由于我的规则而被迫使用 https,但任何对不在“ protected ”文件夹中的图像、样式表和 javascript 的引用仍会被重定向到 http。这会导致“ protected ”页面仅部分安全。在重定向代码之前添加以下内容可解决此问题:
RewriteRule \.(css|gif|jpe?g|js|png|swf)$ - [L]
最佳答案
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} protected [NC,OR]
RewriteCond %{REQUEST_URI} protected2 [NC,OR]
RewriteCond %{REQUEST_URI} protected3 [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [L,R=301]
RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} !protected [NC]
RewriteCond %{REQUEST_URI} !protected2 [NC]
RewriteCond %{REQUEST_URI} !protected3 [NC]
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [L,R=301]
您可以使用OR
添加更多选项!
这里是关于 mod_rewrite 条件的更多细节: http://httpd.apache.org/docs/current/mod/mod_rewrite.html#RewriteCond
关于http - htaccess : force http on all pages and https on select directories,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7059415/