Forcing SSL Protocol Using PHP or Apache's mod_rewrite

There are quite a few circumstances where you may need to force a site, app or page to serve over a secure SSL connection. In PHP development there are two ways to approach this problem depending on your setup. If you’re using Apache to serve your site and you have the ability to use .htaccess files then you can use a rewrite rule to simplify this task server side.

Using Apache mod_rewrite to force SSL

If you can use the mod_rewrite function below to enforce this server side.

Use PHP to force page to serve over SSL

You may be in the position where you only need to redirect a certain page (although you could easily modify the rewrite rule above to do that) or you don’t have the ability to use .htaccess files then you will need to handle this within your actual PHP script.