Forum Moderators: phranque

Message Too Old, No Replies

Redirect http to https and back

redirect to https if a visitor goes to a page and redirect back to http

         

nimonogi

7:52 am on Sep 9, 2009 (gmt 0)

10+ Year Member



Hello,

After browsing the forums i end up writing this code:

# Switch to https
RewriteCond %{httpS} off
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^cart.php?$ [domain.com...] [R=301,L]

# Switch back to http if https request
RewriteCond %{httpS} on
RewriteCond %{REQUEST_URI} !^cart.php?$
RewriteRule (.*) [domain.com...] [R=301,L]

The main idea is to redirect to https when a visitor goes to cart.php and redirect back to http when leaves the page.

Any ideas why the code isn't working?

Thanks.

jdMorgan

6:05 pm on Sep 9, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Try using only the "SERVER_PORT" variable -- On some servers, the "HTTPS" variable is not available when .htaccess is executed.

There were also several other minor problems any of which may have caused the failure.

I'm also assuming that this code goes into your "home page" direcotry .htaccess file, and that you already have other rules in this .htaccess file that work properly, and therefore have already included the directives required to set-up and enabled mod_rewrite.


# Redirect http [b]requests for cart.php (only)[/b] to https
RewriteCond %{SERVER_PORT} !=443
RewriteRule ^cart\.php$ https://www.example.com/cart.php [R=301,L]
#
# Redirect back to http [b]if any URL other than cart.php[/b] is requested using https
RewriteCond %{SERVER_PORT} =443
RewriteCond $1 !^cart\.php$
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

Note that with these simple rules, cart.php must handle serving all included objects (images, external JavaScript files, etc.) required by pages to be displayed in the secure environment. If it does not, then you will get "mixed secure/insecure" warnings in your browser. So, either the script must serve all of these objects in the secure context, or requests for these included-object URLs must be correctly redirected to https (or not redirected to http) by the rules above.

I bolded the comments regarding this issue in the code above.

Jim