Cloudfront Nginx 重写导致问题

Cloudfront Nginx Rewrite Causing Problems

我正在使用 cloudfront 设置 cdn。我的云端分发来源是我的 aws 负载均衡器 (ELB)。当我向云端发出请求而不是获取云端 url (cdn.mysite.com/images/image.jpg) 时,它被重定向到 https://www.alio.com/images/image.jpg。由于我的 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;
    }
}

重写^ https://$host$request_uri?永恒的;更改 url(当我删除重写时,我得到 cdn url)。我有此重写以确保对我网站的所有请求都是 https。如果有一种方法可以代替重写 301 重定向,或者如果我检测到它是云端调用 ELB,则不重写?

您是否已将 CloudFront 配置为将主机 header 列入白名单?

对于每个行为 > 从列表中转发 Headers > Select 'Whitelist' > Select 'Host' 并点击添加。

此设置可确保主机 header (cdn.mysite.com) 包含在返回源的请求中(因此请确保您已将 cdn.mysite.com 添加到您的 server_name 指令)。

如果您只希望通过 TLS 访问您的站点,那么也可能值得考虑使用 HTTP 严格传输安全 header。将以下内容添加到您的配置中应该可以做到:

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

我经常看到这些类型的结构。他们是 Apachism,您应该学会以不同的方式去做。

HTTP 和 https 是协议,因此应该在处理协议的级别进行处理,而不是在处理文档位置的级别进行处理,除非它们是特定于位置的,而在您的情况下它们不是。

这也允许保持事情的清洁,而不是无意中在 http 级别配置一些东西来规避始终 https 逻辑。

所以 https 总是很简单:

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

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

不应该让它变得更复杂:-)