Nginx条件重定向到https

时间:2016-10-21 16:29:29

标签: nginx

我遇到的情况虽然所有流量都应该将http重定向到https,除非上下文是/ publish

http {mydomain.com/*}应强制重定向到https {mydomain.com},但如果网址为http {mydomain.com/publish}则不会,不需要重定向。

提前致谢

2 个答案:

答案 0 :(得分:2)

在nginx中进行重定向的最佳方法是使用多个server{}块。 你可以这样做:

server {
  server_name mydomain.com;
  listen 80;

  location / {
    return 301 https://$server_name$request_uri;
  }
  location /publish {
    # Here goes your usual request handling, with proxying and so on
    # Nested location can be used if needed
  }
}

server {
  server_name mydomain.com;
  listen 443;
  ssl on;
  # Here goes all your request handling 
}

答案 1 :(得分:1)

@Hardy提到的上述代码可以很好地使用两台服务器,另一种方法是将重定向代码放在if块的开头,

server {
  listen 80;
  server_name mydomain.com;
  if ($request_uri ~ "publish") {
    return 301 https://$server_name$request_uri;
  }
  ...
  location / {
    ...
  }
  ...
}

server {
  listen 443;
  server_name mydomain.com;
  ...
}

如果您只需要使用单个服务器,则可以在同一服务器中定义两个端口并使用https所需的代码,然后按以下方式删除第二个服务器

map $request_uri $tmp_do_redirect {
  "~publish" 1;
  default  0;
}
map $scheme $do_redirect {
  "https" 0;
  default  $tmp_do_redirect;
}   
server {
  listen 80;
  listen 443;
  server_name mydomain.com;
  #https code, like ssl, certificate, etc#
  ...
  if ($do_redirect = "1") {
    return 301 https://$server_name$request_uri;
  }
  ...
  location / {
    ...
  }
  ...
}
相关问题