There's several hundred threads with example code. All you'll need to do is substitute localhost for example.com.
There's two parts to the code, one that forces HTTP and one that forces HTTPS. However, it is important that you also link to the correct URL from within your site. The redirect is to correct old links found in search engine listings and so on.
One thing to check, do requests for HTTP and HTTPS resolve to the same folder on the server? That affects how you configure the code.