我正在尝试为多租户Saas设置一个Nginx代理服务器,其中包含许多自定义域名。我想要做的是创建一个服务器块,它可以处理以下请求,所有这些请求都是301永久的:
我目前正在用一些If语句来处理这个问题,但是它看起来很烦人,我希望能以更有效的方式提供一些帮助:
server {
    listen 80 default_server;
    location / {
      # if 'www' redirect to https
      if ($host ~* ^(www)) {
        return 301 https://$host$request_uri;
      }
      # if '*.saas-domain.com' redirect to https://*.saas-domain.com
      if ($host ~* ^(.*)\.saas-domain\.com) {
        return 301 https://$host$request_uri;
      }
      # if not 'www' redirect to https and add 'www'
      if ($host !~* ^(www)) {
        return 301 https://www.$host$1 permanent;
      }
    }
}这是处理我所有场景的最好方法吗?我认为复杂的是通配符自定义域。我关心的是If语句的开销。蒂娅!
发布于 2018-07-01 20:25:15
Nginx建议不要使用"If“语句,除非您没有其他解决问题的方法。我建议为您的域名添加单独的块,因为这将给您提供更多的灵活性。
尝试下面的方法,看看是否有帮助。
# Capture requests that already have www and redirect to https
server {
    listen 80;
    server_name www.*;
    return 301 https://$server_name$request_uri;
}
# Captures the saas-domain.com requests and redirects them
server {
    listen 80 ;
    server_name *.saas-domain.com;
    return 301 https://$server_name$request_uri;
}
# Default capture everything else and redirect to https://www.
server {
    listen 80 default_server;
    server_name _;
    return 301 https://www.$host$request_uri;
}在生产中实现它之前先测试它。
Nginx变量
https://stackoverflow.com/questions/51126322
复制相似问题