Both solutions given by @A.L and @AndreySobkanyuk are valid, but don't apply to the issue I was experiencing.
The problem with both solutions given by @A.L and @AndreySobkanyuk is that Symfony 2 is trying to do a redirect. I.e. if a URL is accessed through a protocol (e.g. HTTP) which in the routing config is specified differently (e.g. HTTPS), Symfony 2 will do a redirect (at a PHP level).
In my situation, the URL rewriting happens at a web server level (Apache) because my website serves all URL's as HTTPS.
The problem I was dealing with was that the URL's generated in my templates were all rendered using the HTTP protocol were they should have been HTTPS. I was assuming that there was a way to tell Symfony that whenever it renders a URL to prefix it with HTTPS instead of HTTP. Unfortunately, there isn't (or at least, not that I'm aware off).
Since my website is running behind a load balancer, my web server wasn't aware that it should render URL's as HTTPS because the internal connection between the load balancer and the web server is HTTP. This means that from Symfony's point of view, all requests are made using HTTP and by forcing the protocol on a Symfony routing level, it was causing an infinite redirect loop, i.e;
- You hit a URL through HTTPS.
- The load balancer passes the request to the web server as HTTP.
- Within Symfony the route is configured to use HTTPS which causes a redirect at a PHP level.
- Back to 1 (infinite loop).
To solve my problem I had to make my web server aware of the fact that my website runs in HTTPS. By following the instructions given on the How to Configure Symfony to Work behind a Load Balancer or a Reverse Proxy page I as able to fix the problem, i.e. my web server is now being supplied with the correct header information and is now generating the correct URL's.
The easiest way to pass on the required headers from the load balancer to the web server is to add the following line to your web/app.php
:
Request::setTrustedProxies(array($request->server->get('REMOTE_ADDR')));
Beware, that the above might not be the best solution for your specific configuration. Please refer to the documentation for other approaches that might be more suitable for your set up.
{{ path() }}
? – A.L{{ url(' ... ') }}
in my Twig templates. – Luke