将HTTP重定向到一页的HTTPS

Ant*_*ony 11 .htaccess ssl https

我知道这个问题已经被要求死亡,但出于某些原因,在我读过的20个帖子中,没有什么能适合我,希望有人可以提供一些见解.

基本上,我有一个简单的购物车,我想将2 uri重定向到HTTPS,我的结帐页面和我的管理文件夹:

/checkout
/admin
Run Code Online (Sandbox Code Playgroud)

我可以使用以下代码成功重定向到HTTPS版本以进行结帐:

RewriteEngine On
#https
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^checkout https://palatinehillsestatewinery.com/checkout [R=301,L]

# remove index.php, this is just included to show everything in my .htaccess
RewriteCond $1 !\.(gif|jpe?g|png)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)$ /index.php/$1 [L]
Run Code Online (Sandbox Code Playgroud)

我在这个和所有其他解决方案中发现的问题是,一旦我决定返回不应该是HTTPS的页面,该网址将保持HTTPS.

我一直在摸索循环等.

如果有人可以帮助在这两个页面上重定向到HTTPS,然后在所有其他页面上重新定向到http,那将是一个很大的帮助,非常感谢.

Laz*_*One 22

这不是直接回答你的问题,但我觉得我把它作为一个答案(加上它太大了,不能发表评论).

我的建议:请停止使用htaccess进行此类任务(强制使用HTTPS的几个URL并强制其余的使用HTTP).

最好的方法是为所有链接(页面,而不是资源)生成FULL URL,其中URL包括域名和协议.在这种情况下,所有URL都将立即具有适当的协议(HTTP/HTTPS).当然:如果通过HTTP请求(出于某种奇怪的原因),您仍然可以修复(301或302重定向)请求到应该是https.这就是.htaccess可以安全,轻松地使用的地方.

如果用户将通过HTTPS请求正常页面(应该通过HTTP提供) - 那么让他这样做 - 这没有任何问题.是 - HTTPS在服务器端需要更多资源,但如果以这种方式生成所有链接,除非用户专门更改协议,否则几乎不会出现这种情况.即使这样的一个页面将通过HTTPS提供,他点击的下一个"普通"链接将是HTTP - 1个额外的基于HTTPS的页面视图不会杀死您的服务器.

我一直在使用这种方法,当网站有安全区域时...根据日志,我们有不到0.01%的所有页面浏览量被查看/试图通过"错误"协议查看 - 绝大多数他们是机器人或企图破解/漏洞搜索.

基于这样的统计数据,我会说 - 它运作得很好.是的 - 你需要改变你的代码/模板来实现这一点..但它比使用.htaccess和mod_rewrite更好.


在任何情况下,以下是为您完成工作的规则:

# force https for all URLs in /checkout
RewriteCond %{HTTPS} =off
RewriteRule ^checkout https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# don't do anything for images/css/js
RewriteRule \.(gif|jpe?g|png|css|js)$ - [NC,L]

# force http for all other URLs that are not in /checkout
RewriteCond %{HTTPS} =on
RewriteCond %{REQUEST_URI} !^/(checkout|index.php/checkout)
RewriteRule .* http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# your other rules here, e.g.:
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)$ /index.php/$1 [L]
Run Code Online (Sandbox Code Playgroud)

要么

# force https for all URLs in /checkout
RewriteCond %{HTTPS} =off
RewriteRule ^checkout https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# do not do anything for already existing files
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .+ - [L]

# force http for all other URLs that are not in /checkout
RewriteCond %{HTTPS} =on
RewriteCond %{REQUEST_URI} !^/checkout
RewriteRule .* http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# your other rules here, e.g.:
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)$ /index.php/$1 [L]
Run Code Online (Sandbox Code Playgroud)