如何有选择地重定向到https / http

时间:2014-06-19 05:31:19

标签: apache .htaccess redirect https rewrite

我需要将网站中的一些页面合并到https。现在我想要两个案例。

  1. 如果页面REQUEST_URI是用户,则用户/登录,用户/注册,购物车,结帐和原始协议是http。应该重定向到https。
  2. 如果页面REQUEST_URI不是用户,用户/登录,用户/注册,购物车,结帐和原始协议是https。应该重定向到http。
  3. 所以我实施了以下规则。

    # Block 1 - Forcing HTTPS
    RewriteCond %{HTTPS} !=on [OR]
    RewriteCond %{SERVER_PORT} 80
    
    # Forcing HTTPS
    RewriteCond %{SERVER_PORT} !^443$
    RewriteCond %{REQUEST_URI} ^/cart  [OR]
    RewriteCond %{REQUEST_URI} ^/checkout  [OR]
    RewriteCond %{REQUEST_URI} ^/user/login [OR]
    RewriteCond %{REQUEST_URI} ^/user [OR]
    RewriteCond %{REQUEST_URI} ^/user/register
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,QSA,L]
    
    
    # Block 2 - Forcing HTTP
    RewriteCond %{HTTPS} !=off [OR]
    RewriteCond %{SERVER_PORT} 443
    
    RewriteCond %{SERVER_PORT} !^80$
    RewriteCond %{REQUEST_URI} !^/cart 
    RewriteCond %{REQUEST_URI} !^/checkout 
    RewriteCond %{REQUEST_URI} !^/user/login
    RewriteCond %{REQUEST_URI} !^/user
    RewriteCond %{REQUEST_URI} !^/user/register
    RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,QSA,L]
    
    
    # The following rule tells Apache that if the requested filename
    # exists, simply serve it.
    RewriteCond %{REQUEST_FILENAME} -s [OR]
    RewriteCond %{REQUEST_FILENAME} -l [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^.*$ - [NC,L]
    # The following rewrites all other queries to index.php. The 
    # condition ensures that if you are using Apache aliases to do
    # mass virtual hosting, the base path will be prepended to 
    # allow proper resolution of the index.php file; it will work
    # in non-aliased environments as well, providing a safe, one-size 
    # fits all solution.
    RewriteCond %{REQUEST_URI}::$1 ^(/.+)(.+)::\2$
    RewriteRule ^(.*) - [E=BASE:%1]
    RewriteRule ^(.*)$ %{ENV:BASE}index.php [NC,L]
    

    这里我遇到问题,如果启用了两个块中的一个功能,则根据规则顺利运行。但是如果两者都被启用,则递归重定向开始发生。我需要两种功能。如果可以通过.htaccess规则?

    更新:类似的问题在SO上被称为how in htaccess can i redirect the user to https from http and back again。但它只有一个答案,建议继续推进应用。

    更新2:添加了Zend Framework Application默认.htaccess规则

1 个答案:

答案 0 :(得分:1)

你让它变得非常复杂。像这样简化你的规则:

RewriteEngine On

# Block 1 - Forcing HTTPS
RewriteCond %{HTTPS} off [OR]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(cart|checkout|user|user/login|user/register)/?$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,NC,NE,L]

# Block 2 - Forcing HTTP
RewriteCond %{HTTPS} on [OR]
RewriteCond %{SERVER_PORT} 443
RewriteRule !^(cart|checkout|user|user/login|user/register)/?$ http://%{HTTP_HOST}%{REQUEST_URI} [R=301,NC,NE,L]

确保在新浏览器中进行测试,以避免301缓存问题。