2

I am setting up a cdn using cloudfront. My origin for my cloudfront distribution is my aws load balancer (ELB). When I make a request to cloudfront instead of getting the cloudfront url (cdn.mysite.com/images/image.jpg) it is being redirected to https://www.alio.com/images/image.jpg. I figured out why it is doing this due to my nginx.conf:

server {
    root /var/www/html/alio/public;
    index index.php;

    server_tokens off;

    server_name www.alio.com;

    location / {
        if ($http_x_forwarded_proto != 'https') {
            rewrite ^ https://$host$request_uri? permanent;
        }
        try_files $uri $uri/ /index.php?$query_string;
    }
    location ~ \.php$ {
        try_files $uri /index.php =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

The rewrite ^ https://$host$request_uri? permanent; changes the url (when i delete the rewrite i get the cdn url). I have this rewrite to ensure that all requests to my site are https. If there a way to do instead of a rewrite a 301 redirect or not do this rewrite if I detect it's cloudfront making the call to the ELB?

2 Answers 2

4

Have you configured CloudFront to whitelist host headers?

For each behaviour > Forward Headers > Select 'Whitelist' > Select 'Host' from the list and hit Add.

This setting ensures that the host header (cdn.mysite.com) is included in requests back to the origin (so make sure you've added cdn.mysite.com to your server_name directive).

It might also be worth considering using the HTTP Strict Transport Security header if you only want your site accessed over TLS. Adding the following to your config should do it:

add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
0
1

I see these types of constructs a lot. They're Apachisms that you should learn to do differently.

Http and https are protocols and as such should be handled at the level where the protocol is handled, not where the document location is handled, unless they a are location specific, which in your case they are not.

This also allows to keep things clean and not inadvertently configure something on the http level that circumvents the always https logic.

So always https is simple:

server {
    listen 80;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ... ;
    ....
}

Should not make it more complicated :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.