强制某些URL上的HTTPS并强制所有其他URL使用HTTP

时间:2010-07-22 08:29:19

标签: apache http mod-rewrite https

我有一个客户端项目,我需要为某个文件夹强制使用HTTPS,并强制所有其他文件夹使用HTTP。我可以成功地为我想要的文件夹强制执行HTTPS,但所有链接回到网站的其余部分最终都是通过HTTPS。我想有一条规则强制请求安全文件夹中的任何“不”被强制回HTTP。这是我到目前为止所做的:

RewriteEngine On
RewriteCond $1 !\.(gif|jpe?g|png)$ [NC]

RewriteCond %{HTTPS} !=on
RewriteRule ^(my) https://%{HTTP_HOST}%{REQUEST_URI} [NC,R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1

'my'是我需要强制使用HTTPS的文件夹的名称。

有什么想法吗?

更新:我也尝试过:

RewriteEngine On
RewriteCond $1 !\.(gif|jpe?g|png)$ [NC]

# Force HTTPS for /my
RewriteCond %{HTTPS} !=on
RewriteRule ^(my) https://%{HTTP_HOST}%{REQUEST_URI} [NC,R=301,L]

# Force HTTP for anything which isn't /my
RewriteCond %{HTTPS} =on
RewriteRule !^my http://%{HTTP_HOST}%{REQUEST_URI} [NC,R=301,L]

# Remove index.php from URLs
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1

但是,不是通过HTTPS强制执行/我的请求,而是现在只需解析为http://www.example.com/index.php/my

4 个答案:

答案 0 :(得分:16)

啊,当然。问题在于,重写规则集在初始重定向后转换为index.php后将被重新处理。使用您当前拥有的内容,您需要另外调整重定向,以确保在重写为/index.php/my后不会应用这些重定向。

以下内容应该如下:

RewriteEngine On
RewriteCond $1 !\.(gif|jpe?g|png)$ [NC]

# Force HTTPS for /my
RewriteCond %{HTTPS} !=on
RewriteCond %{THE_REQUEST} ^[A-Z]+\s/my [NC]
RewriteRule ^(my) https://%{HTTP_HOST}%{REQUEST_URI} [NC,R=301,L]

# Force HTTP for anything which isn't /my
RewriteCond %{HTTPS} =on
RewriteCond %{THE_REQUEST} !^[A-Z]+\s/my [NC]
RewriteRule !^my http://%{HTTP_HOST}%{REQUEST_URI} [NC,R=301,L]

# Remove index.php from URLs
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1

答案 1 :(得分:4)

尝试以下内容,应该适合您:

RewriteEngine On

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

RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} !^/my
RewriteRule ^(.*)$ http://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

答案 2 :(得分:1)

这可以在旧的客户网站上使用,并且可以适应您的目的:

#If https off and in the cart dir
RewriteCond %{HTTPS} =off [NC]
RewriteCond %{REQUEST_URI} ^/cart/(.*) [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}/cart/%1 [R=301,L]

#If https on and not in cart dir    
RewriteCond %{HTTPS} =on
RewriteCond %{REQUEST_URI} !^/cart [NC]
#Above line actually used to read RewriteCond %{REQUEST_URI} !^/cart|media|images|thumbs|css|js [NC]
#to allow js/css/images to be served so there were no mixed ssl messages popping up to visitors
RewriteCond %{REQUEST_FILENAME} !index\.php$ [NC]
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

用我的

取代购物车

答案 3 :(得分:0)

只是颠倒条件:

RewriteCond %{HTTPS} =on
RewriteRule !^my http://%{HTTP_HOST}%{REQUEST_URI} [NC,R=301,L]