I would like to force HTTPS and the apex domain (e.g. https://example.com) in my application through nginx configuration using location blocks. I currently have the following nginx_app.conf file (which works with both the apex and the www subdomain, and both http and https):
location / { try_files $uri @rewriteapp; } location @rewriteapp { rewrite ^(.*)$ /app.php/$1 last; } location ~ ^/(app|config)\.php(/|$) { # fastcgi_pass directives go here... } To force the apex domain and https, I tried using if-statements as follows, checking for the $scheme and $host variables, but I get an error that the page is not redirecting properly. I also added an HSTS directive.
location / { if ($scheme = http) { rewrite ^/(.*) https://$host/$1 permanent; } if ($host = www.example.com) { rewrite ^/(.*) https://example.com/$1 permanent; } try_files $uri @rewriteapp; } location @rewriteapp { rewrite ^(.*)$ /app.php/$1 last; } location ~ ^/(app|config)\.php(/|$) { # fastcgi_pass directives go here... add_header Strict-Transport-Security "max-age=86400"; } What is the proper way to force http and the apex domain with nginx configuration? As an aside, I'm using heroku (with DNSimple) to deploy my app so I would like both the following domains to work: https://example.herokuapp.com and https://example.com.
UPDATE: I tried moving the if-statements outside the location block into the default server block (click here), and change the rewrites for returns as follows, but it still does not work. I still get "The page isn't redirecting properly" when requesting http, and "Unable to connect error" when requesting the www subdomain.
if ($scheme = http) { return 301 https://$host$request_uri; } if ($host = www.example.com) { return 301 https://example.com$request_uri; } location / { try_files $uri @rewriteapp; } location @rewriteapp { rewrite ^(.*)$ /app.php/$1 last; } location ~ ^/(app|config)\.php(/|$) { # fastcgi_pass directives go here... add_header Strict-Transport-Security "max-age=86400"; }
locationswithserver_nameand the rightlistendirective for each HTTP scheme.listendirective in the location block. In the official documentation for listen it indicates that it is used under the context ofserver. I'm using Heroku and I don't think I can modify the server block, that's why I'm asking for a solution usinglocationblocks...