Nginx,authentication和强制HTTPS – 作为包含片段?

有点卡在这里。 我想要一个漂亮简单的Nginx“include”代码片段,它需要HTTP AUTH来包含它所在的位置,并强制redirect到HTTPS(如果还没有的话)。

我想出了这个:

# /etc/nginx/snippets/requirelogin-staff.conf if ($https != "on") { return 301 https://$server_name$request_uri; } auth_ldap "Login Required"; auth_ldap_servers staff; 

并像这样使用它(愚蠢的例子为了简洁起见,现实世界中我们有django服务/和/静态/作为资源文件的快捷方式):

 location / { include snippets/requirelogin-staff.conf; try_files $uri $uri/index.html $uri.html =404; location /static { alias /var/www/webroot/liv/static; } } 

它适用于任何由位置/

wget -S显示它首先发出301redirect到相同的URL,但与https协议。 然后它回来了一个401正确。

问题是/静态下的URL

auth通过指令inheritance踢进来。

但是,似乎“if($ https!=”on“)…”没有被inheritance到嵌套的位置块中。

所以wget -S会直接进入401,邀请用户使用不安全的连接login,这当然是一件坏事。

我可以看看为什么“如果”有问题(try_files不会inheritance)。

但是,这让我颇为困惑。

任何一种灵魂都可能提出一种更清洁的方法吗 一个原则是(理想情况下)我希望AUTH在一个或多个位置被一条整齐的单行“包含”所需,以避免错误。

inheritance将是很好的 – 再次避免错误。 当然,我们可以在每个位置块上运行这个“包含”,它确实有效。 但是如果我们守卫“/”,我们很高兴知道我们已经保护了整个网站,并且一个开发者无意中添加了另一个位置块,不能突然打开一个安全漏洞。

非常感谢,

蒂姆

iftry_filesproxy_passuwsgi_pass等命令不会被嵌套的位置块inheritance。 像auth_ldap其他设置是inheritance的。

https://stackoverflow.com/a/32126596

我无法find什么types的configuration语法是“命令”,哪些是常规configuration项的官方文档。 嵌套位置的inheritance行为似乎没有logging。

更清洁的方法

不要使用嵌套的位置,因为inheritance行为是没有logging的,没有人会对将来做出改变有信心。 简单地重复自己,但重复自己与包括。 也许你可以创build另一个包含“standard-behavior.conf”的东西,并把try_files放在那里。

 location /static { include snippets/requirelogin-staff.conf; try_files $uri $uri/index.html $uri.html =404; alias /var/www/webroot/liv/static; } location / { include snippets/requirelogin-staff.conf; try_files $uri $uri/index.html $uri.html =404; } 

301redirect可以强制你的整个网站使用https,如果这是有意的,那么你不应该提供任何服务,除了301redirect通过端口80,

 { # Http Redirect listen 80 default_server; listen [::]:80 default_server; server_name _; return 301 https://$server_name$request_uri; } 

只要记住,如果你使用301指令,那么一切都必须是HTTPS,并且每个子域也必须是HTTPS – 不是一件坏事。 在你使用网站定义之前,再仔细检查一下server_name的定义是否正确 – 我没有看到你的configuration文件。