让 nginx 将所有内容重定向到 https,除了一个目录

sca*_*che 4 nginx redirect 301-redirect

我需要 nginx 将所有 http URL 重定向到 https,但“.secret/”目录除外,该目录应继续用作 http。

因此,例如:

  • http://example.com/a.html --> https://example.com/a.html
  • http://example.org/z/b.html --> https://example.org/z/b.html
  • http://example.com/.secret/x.html --> http://example.com/.secret/x.html

我的配置中有以下内容,但对于 http,它返回包含“_”的地址。

server {
    listen 80;
 
    server_name _;
 
    location /.secret {
        return http://$server_name$request_uri;
    }
 
    location / {
        return 301 https://$server_name$request_uri;
    }
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

更新:

结合@mforsetti 和@Pothi_Kalimuthu 的评论,以下内容有效:

server {
    listen 80;
 
    server_name _;
 
    location /.secret { }
 
    location / {
        return 301 https://$host$request_uri;
    }
}
Run Code Online (Sandbox Code Playgroud)

mfo*_*tti 5

它返回包含“_”的地址。

server_name _;

location /.secret {
   return http://$server_name$request_uri;
}
Run Code Online (Sandbox Code Playgroud)

$server_name返回分配server_nameserver块,在您的情况下是_; 因此_返回的地址。

如果您希望它返回主机名或Host请求标头,请尝试使用$host,例如:

location /.secret {
    return http://$host$request_uri;
}
Run Code Online (Sandbox Code Playgroud)

.secret/ 应继续用作 http 的目录

如果要提供目录,请指定root目录。

location /.secret {
    root /path/to/your/parent/of/secret/directory;
}
Run Code Online (Sandbox Code Playgroud)