Nginx 无法在代理模式下将 HTTP 重定向到 HTTPS

Nginx 无法在代理模式下将 HTTP 重定向到 HTTPS

当我使用 https 协议访问时,它可以工作。但是当我使用 http 协议访问时,它根本不起作用。

我的 Nginx 版本是 1.12.1。配置如下:/etc/nginx/sites-available/***:

server {
    listen 80;
    server_name ***;
    client_max_body_size 10240M;

    location / {
        proxy_pass http://localhost:8080/guacamole/;
        proxy_buffering off;
        proxy_http_version 1.1;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $http_connection;
        proxy_cookie_path /guacamole/ /;
        access_log off;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/***/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/***/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot

    if ($scheme != "https") {
        return 301 https://$host$request_uri;
    } # managed by Certbot
}

答案1

我会打开 nginx 的调试日志并跟踪当您尝试使用 http 访问您的页面时实际发生的情况。

我也不建议在 nginx 中使用 IF 语句来实现你想要实现的目标。尝试将虚拟主机拆分为两个服务器部分:

server {
    listen 80;
    server_name ***;
    rewrite ^ https://***$uri permanent;
}
server {
    listen 443 ssl;
    ssl_certificate /etc/letsencrypt/live/***/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/***/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    server_name ***;
    client_max_body_size 10240M;

    location / {
        proxy_pass http://localhost:8080/guacamole/;
        proxy_buffering off;
        proxy_http_version 1.1;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $http_connection;
        proxy_cookie_path /guacamole/ /;
        access_log off;
    }
}

相关内容