多个htaccess重定向,http到https但页面除外

时间:2016-02-19 03:19:19

标签: php apache .htaccess redirect mod-rewrite

我使用mod_rewrite来允许“友好的URLS”替换搜索参数,这很好。 但是我现在需要将所有流量重定向到https://但只允许一些页面保留在http:// (我需要这样做,所以我的推荐是由我发送流量的网站收集的)

多年来我已经添加到.htaccess文件中,大多数工作正常,但我不完全理解它,所以它可能会变得混乱: - (

我有以下(我已经删除了任何我认为不相关的内容)

<IfModule mod_rewrite.c>
  Options +FollowSymlinks
  RewriteEngine On
</IfModule>

<IfModule mod_rewrite.c>
  RewriteCond %{SCRIPT_FILENAME} -d [OR]
  RewriteCond %{SCRIPT_FILENAME} -f
  RewriteRule "(^|/)\." - [F]
</IfModule>

<IfModule mod_rewrite.c>

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^profile/([A-Za-z0-9'/-]+)-([0-9]+)$ profile.php?id=$2 [NC,L,QSA]
# NOTE: this allows for profile.php?id=123 to be replaced with /profile/name-123

# redirects any http:// traffic to https://
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

</IfModule>

以上工作正常,但所有页面都重定向到https

我尝试将https重定向部分添加/更改为允许urlout.php不被重定向,但这只是循环,我得到一个浏览器警告页面有太多的重定向: - (

# redirects any http:// traffic to https://
RewriteCond %{HTTPS} !on
RewriteCond ${REQUEST_URI} !^/urlout\.php
#RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI}  [R=301,L]

我也尝试过其他一些东西,但他们要么不重定向,一切都转到https,否则我会出现循环错误或内部500错误......

基本上我希望所有页面都转到https,但不是urlout.php

对上述任何代码的任何建议都非常感谢!

2 个答案:

答案 0 :(得分:1)

回答我自己的问题:

我设法做到这一点,在第一个条件之后我没有添加[NC]是一个愚蠢的错误......

但是,对于其他人,以下代码将从http://将ALL重定向到https://,但1页除外(在我的情况下为urlout.php)

# redirects any http:// traffic to https:// with exception of urlout.php
RewriteCond %{HTTPS} off [NC]
RewriteCond %{REQUEST_URI} !^/urlout\.php [NC]
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] 

我需要这样做,以便我发送流量的网站可以将我的域名视为&#34; HTTP引荐来源&#34;。

然而,我发现了一种更简单的方法将引用者从https传递到http(尽管特定于浏览器!)添加到HTML头:

<meta name="referrer" content="origin">

我的答案是(除其他外):moz.com's Meta Referrer Tag Blog Post

答案 1 :(得分:0)

如果您想将某些空间页面重定向到https,例如,要重定向:

要 - https://www.example.com/page2.html

您可以尝试以下方法:

 RewriteEngine on

 RewriteCond %{HTTPS} off
 RewriteRule ^(page|page2)\.html$ https://www.example.com/$1.html [L,R]

如果要将整个站点从http重定向到https,可以使用以下命令:

 RewriteEngine on



 RewriteCond %{HTTPS} off
 RewriteRule ^(.*)$ https://www.example.com/$1 [NC,L,R]

RewriteCond%{HTTPS} off 对于避免重定向循环非常重要,因为它会跳过https请求的规则。