Redirect to https

Is there a correct way/place to globally redirect from http to https?

I’m currently doing it in my .htaccess file but I would prefer to do it in the code and make it a per-server config setting.

I use the Security component for this. See the second example in the “Usage” section.

I implemented this and found it broke my controllers’ return this->redirects
as in, they didn’t redirect at all. Flash worked, but no redirect.

Can you specify why not/can’t do it on the .htaccess? I don’t know what you mean by “per-server” (do you have multiple applications in the same domain?)
I prefer it because is transparent for the application.

I have a single codebase with an admin page to automatically “publish” code updates from Dev to Test, and then from Test to Production (and other flavors as well). Along the way, not all servers will have HTTPS running.

If I use .htaccess, the .htaccess file gets copied over as part of it. So I don’t want to have SSL redirects that fail on non-HTTPS servers. I tried looking up a way to implement server-dependent SSL redirects, but came up empty handed. It seems like .htaccess can either check for SSL status or server name, but not both.

What would be a concrete example of a link that needs to be http on one server and https on another?

I have a couple of sites where I work on a non-ssl dev environment and upload to a server with ssl, but since relative urls resolve appropriately by default I never had any reason to do any kind of manual configuration…

In my case, the client wants to require SSL on the production server but not on a demonstration server.

So we have two different .htaccess files in webroot. In one case, it forces SSL if the user neglected to type https or followed a link from an email without it — in the other case, it doesn’t enforce SSL because the server doesn’t support it and it would cause errors.

Oh, I see, I didn’t totally get your question XD

So if you want to redirect to http or https in your code instead of an .htaccess, you should do it in the AppController’s beforeFilter.

Something along the lines of this should do the trick:

if ( !$this->request->is('ssl') )
		$this->redirect( str_replace('http://', 'https://', Router::url('', true )) );

Pretty basic and self-explanatory. You can combine that with your config quite easily.

EDIT: Actually, Router::url() is no good since it doesn’t contain params, so something simpler, albeit less cake-y makes more sense:

if ( !$this->request->is('ssl') ){

	$schema = 'https://';

	$this->redirect( $schema . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );

This is easier to work with, though, since there’s no need to replace anything.

1 Like