Friday, June 23, 2017

heroku - Redirect to HTTPS and Apex Domain with Nginx location Configuration

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";
}

No comments:

Post a Comment

linux - How to SSH to ec2 instance in VPC private subnet via NAT server

I have created a VPC in aws with a public subnet and a private subnet. The private subnet does not have direct access to external network. S...