简体   繁体   中英

Apache redirect one page to HTTP or HTTPS conditionally

The home page of our site doubles as both the login page and the main page where users can click links to content. I'm trying to make it so that when the home page is acting as the login page, it is using HTTPS and using HTTP on all other occasions. The home page acts as the login page when there is no user currently logged in (and I can check a cookie for this):

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_COOKIE} ^((?!MY_LOGIN_COOKIE_NAME).)*$ # Cookie is not present
RewriteRule ^/?$ https://%{SERVER_NAME} [R,L] # Redirect http://example.com to https://example.com

This brings an anonymous user to an SSL home page, as expected.

The problem is when the cookie does exist, how do make requests for the home page always redirect to the HTTP version and not the HTTPS version? (After a user logs in, they are taken back to the home page, but now it would show content).

I tried appending this to the end of the rules above:

RewriteCond %{HTTP_COOKIE} ^.*MY_LOGIN_COOKIE_NAME=([^;]+) # Cookie exists
RewriteRule ^/?$ http://%{SERVER_NAME} [R,L] # Redirect home page to HTTP only

This results in a redirect loop error, most likely because the regex matches the home page, redirects to http version, matches again, redirects to http version . . . infinitely.

Is there a way to make the home page redirect to HTTPS when the cookie is missing and to HTTP when it is present?

Can yo try these 2 rules:

RewriteEngine On

RewriteCond %{SERVER_PORT} !=443
RewriteCond %{HTTP_COOKIE} !MY_LOGIN_COOKIE_NAME [NC]
RewriteRule ^/?$ https://%{SERVER_NAME} [R,L]

RewriteCond %{SERVER_PORT} =443
RewriteCond %{HTTP_COOKIE} MY_LOGIN_COOKIE_NAME [NC]
RewriteRule ^/?$ http://%{SERVER_NAME} [R,L]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM