Nginx:将 http 重定向到 https

Nginx:将 http 重定向到 https

我知道这个问题已经被问过无数次了。但我仍然无法用目前看到的答案来解决问题。

我正在尝试使用 nginx 强制将 http 重定向到 https。当我访问 https//subdomain.example.com 时,一切正常,但访问http://subdomain.example.com 给我

 "This Webpage has a redirect loop"

我试过

rewrite ^(.*) https://$host$1 permanent;

return 301 https://www.mydomain.com$request_uri;

尝试过

proxy_set_header X-Forwarded-Proto $scheme;

没有解决问题。请问我该如何解决这个无限循环的问题?

这是我的 nginx.conf

upstream unicorn {
server unix:/tmp/unicorn.example.sock fail_timeout=0;
}

server {
server_name subdomain.example.com;
listen 80;
return 301 https://$host$request_uri;
root /home/deploy/apps/example/current/public;

location ^~ /assets/ {
gzip_static on;
expires max;
add_header Cache-Control public;
proxy_set_header        X-Forwarded-Proto $scheme;
}

try_files $uri/index.html $uri @unicorn;
location @unicorn {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://unicorn;
}

 error_page 500 502 503 504 /500.html;
 client_max_body_size 4G;
 keepalive_timeout 10;
}


server {
server_name subdomain.example.com;
listen 443;
root /home/deploy/apps/example/current/public;

location ^~ /assets/ {
gzip_static on;
expires max;
add_header Cache-Control public;
}
error_page 500 502 503 504 /500.html;
client_max_body_size 4G;
keepalive_timeout 10;
ssl on;
ssl_certificate /home/deploy/apps/example/shared/ssl_cert.crt;
ssl_certificate_key /home/deploy/apps/example/shared/ssl_private_key.key;
}#

答案1

这很可能是由于您的代理目标,因为您禁用了proxy_redirect

另外,为什么你们不提供所有 HTTPS 服务?

混合使用两者可能会使浏览器警告让访问者感到困惑。

upstream unicorn {
    server unix:/tmp/unicorn.example.sock fail_timeout=0;
}


server {

    server_name _;
    listen 80 default_server;
    return 301 https://subdomain.example.com$request_uri;

}


server {

    server_name subdomain.example.com;
    listen 443 ssl;
    ssl_certificate /home/deploy/apps/example/shared/ssl_cert.crt;
    ssl_certificate_key /home/deploy/apps/example/shared/ssl_private_key.key;
    root /home/deploy/apps/example/current/public;

    client_max_body_size 4G;
    error_page 500 502 503 504 /500.html;
    keepalive_timeout 10;

    location /assets {
        expires max;
        gzip_static on;
        add_header Cache-Control public;
    }

    location / {
        try_files $uri/index.html $uri @unicorn;
    }

    location @unicorn {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_pass http://unicorn;
    }

}

这应该可以做到,除非你的代理目标在缺少 X-Forwarded-Proto 标头的情况下做了一些奇怪的事情,在这种情况下将后备更改为此并希望它能正确处理重定向:

location @unicorn {
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_pass http://unicorn;
    proxy_redirect off;
}

相关内容