【问题标题】:nginx: how to redirect to https while still serving one directory via http?nginx:如何在仍然通过 http 服务一个目录的同时重定向到 https?
【发布时间】:2017-08-10 16:17:51
【问题描述】:

我想阻止人们通过 http 使用我的网站并强制他们使用安全连接。我的 https 证书由letsencrypt(通过webroot 选项)颁发,这意味着它们通过http 连接,我提供来自/.well-known/acme-challenge/ 的静态内容。所有其他请求都应重定向到使用 https。按照我的 nginx.conf 的相关部分

server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com admin.example.com;
    location /.well-known/acme-challenge {
        root /app;
        access_log on;
        try_files $uri $uri/ =418;
    }

    return 301 https://$server_name$request_uri;
}

此 https 升级工作正常,所有用户都能按预期获得 https 连接。问题是,nginx 会升级每个发出的请求,甚至是来自letsencrypt 的请求,这会导致letsencrypt 失败——它甚至不尝试提供文件(文件存在!)。

我如何确保如果请求通过 http 发送到 example.com/.well-known/acme-challenge/[HASH],它将在找到文件时提供文件或返回 418 错误,同时将所有其他不以 /.well-known/acme-challenge 开头的请求升级到 https?感谢您的任何建议

【问题讨论】:

    标签: http nginx https lets-encrypt nginx-location


    【解决方案1】:

    return 301 在服务器范围内,这不是您想要的。将return 放在默认位置:

    location / {
        return 301 https://$server_name$request_uri;
    }
    

    【讨论】:

    • 一定是深夜,因为这是我“最初”拥有的,但有些东西不起作用,所以我根据找到的资源对其进行了更改。现在醒了,这显然按预期工作!谢谢你让我看到隧道里的光;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 2017-05-25
    • 2015-02-18
    • 2017-07-09
    • 2017-10-10
    • 2022-08-14
    相关资源
    最近更新 更多