Nginx:在一条path上强制使用SSL,在其他path上使用非SSL

我如何设置Nginx的conf文件来强制SSL在我的网站上的其中一个path和所有其余的SSL?

例如,我希望/ user下的所有URL都是https,但是其余所有URL都是http。

对于第一部分我有:

rewrite ^/user(.*) https://$http_host$request_uri?; 

我不想用“如果”。 我认为它会利用操作的顺序,但我不想最终在一个循环。

在你的nginxconfiguration中,你应该有两个“服务器”区域。 一个用于端口80,另一个用于端口443(非SSL和SSL)。 只需在您的非SSL网站上添加一个位置即可redirect到您的SSL页面。

 server { root /var/www/ location / { } location /user { rewrite ^ https://$host$request_uri? permanent; } } 

它会将以/ user身份结束的所有stream量转发到您的https://服务器。

然后,在你的443服务器上,你做的是相反的。

 server { listen 443; root /var/www/ location / { rewrite ^ http://$host$request_uri? permanent; } location /user { } } 

Nginx允许在同一个server块中处理HTTP和HTTPS。 因此,您不必为两者重复指令,并可以redirect您要保护的path

 server { listen 80 default_server; listen 443 ssl; ... ssl certificate and other configs ... location /user { if ($scheme = 'http') { rewrite ^ https://$http_host$request_uri? permanent; } } ... your basic configuration ... } 

一定不要ssl on那里,因为它会破坏纯HTTP。

或者,您可以将所有其他来自HTTPS的请求redirect回到HTTP:

 if ($scheme = 'https') { rewrite ^ http://$http_host$request_uri? permanent; } 

更新 :正如Alexey Ten在评论部分指出的那样,每个请求的检查scheme并不是一个非常好的主意。 你应该按照声明的方式来configuration你的nginx。 在这种情况下,声明两个服务器块的locationredirect,将公共逻辑移动到一个单独的文件,并将其include在两个。 所以GruffTech的答案是更好的。