.htaccess - 仅使用 .htaccess 在某些页面上将 http 重写为 https

标签 .htaccess mod-rewrite ssl https

我知道有很多关于我的问题的话题。我检查了所有这些并尝试了它们,但无法使其工作。 我只需要在某些页面上将 http 重写为 https 。访问 https 页面后,URL 将返回到 http。 这是我到目前为止所拥有的:


# Rewrite Rules for domain.com
RewriteEngine On
RewriteBase /

#Rewrite www to domain.com
RewriteCond %{HTTP_HOST} ^www\.domain\.com [NC]
RewriteRule ^(.*)$ http://domain.com/$1 [L,R=301]

#Rewrite to https
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} /secure.php
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L]

#traffic to http://, except secure.php
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} /secure.php
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L]

当我跳过最后一组规则(流量到 http://,secure.php 除外)时,secure.php 页面会加载为 https 并进行加密。美好的。使用最后一组规则(流量为 http://,secure.php 除外),URL 重写为 https,变为蓝色(SSL)一秒钟,然后消失(无 SSL),但 URL 仍然是 https。

有什么想法吗? 雅采克

最佳答案

第三组规则有错误。 解决方案如下:使用第三组规则:如果 https 为“on”,则如果 URL 不包含“/secure”,则重定向到 http。

# Rewrite Rules for domain.com
RewriteEngine On
RewriteBase /

#Rewrite www to domain.com
RewriteCond %{HTTP_HOST} ^www\.domain\.com [NC]
RewriteRule ^(.*)$ http://domain.com/$1 [L,R=301]

#Rewrite to https
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} /secure.php
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L]

#traffic to http://, except secure.php
RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} !(/secure.php)
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [L]

题外话建议:请查找 Yahoo Slow 以及他们关于网站优化的非常聪明的建议,您就会明白为什么前面加上“www”总是更好。您最好对 #1 重写规则执行相反的操作:如果没有“www”,则添加它。


请尝试使用RewriteLog指令:它可以帮助您追踪此类问题:

# Trace:
# (!) file gets big quickly, remove in prod environments:
RewriteLog "/web/logs/mywebsite.rewrite.log"
RewriteLogLevel 9
RewriteEngine On

告诉我它是否有效。

关于.htaccess - 仅使用 .htaccess 在某些页面上将 http 重写为 https,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2357455/

相关文章:

php - 特定目录和文件的 Apache 动态 IP 白名单

ssl - 您可以将 SSL 放在 IP 地址上还是仅放在 Web 服务器的域名上?

ssl - 间歇性 SSL 握手错误 nginx

ssl - 在 Vert.x 上将 SSL 协议(protocol)限制为 TLS 1.2

apache - 我可以使用 .htaccess 重定向到目录中的最新文件吗?

php - laravel 的组域路由在 laragon 中不起作用

.htaccess RewriteRule 返回空白页

php - Wordpress - 在 url 中重写或隐藏 wp-json

php - 从网址中删除/重定向index.php以防止重复的网址

ssl - 如何防止 Nginx 将位置重定向到配置的 proxy_pass url 和端口号