NGINX + RegEx:将 sub2.sub1.example.com 重定向到 sub1.example.com

NGINX + RegEx: redirect sub2.sub1.example.com to sub1.example.com

如何同时使用 regexnginx 以便它们都重定向到同一端点?

  1. http://sub1.example.com
  2. http://sub2.sub1.example.com
  3. http://sub3.sub2.sub1.example.com
  4. https://sub1.example.com
  5. https://sub2.sub1.example.com
  6. https://sub3.sub2.sub1.example.com

----全部解析为---> https://sub1.example.com

我当前的配置(仅适用于情况 2 和 3):

# Default server configuration

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name ~^(.*)\.(?<subdomain>\w+).example\.com$;
    return 301 https://$subdomain.example.com$request_uri; 
}


server {    
    # SSL configuration
    listen 443 ssl default_server;
    listen [::]:443 ssl default_server;
    #
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    #
    root /var/www/html; 

    server_name *.example.com;
    
    location / { ..... localhost:3000
    

然后在另一个文件中:

server {
    # Redirect all http traffic to https
    listen 80;
    listen [::]:80;

    server_name example.com www.example.com;    

    return 301 https://$host$request_uri;
}

server {    
    # SSL configuration 
    listen 443 ssl;
    listen [::]:443 ssl;
    #
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    #
    
    root /var/www/html;

    server_name example.com www.example.com ;

    if ($http_x_forwarded_proto = "http") {
      return 301 https://$server_name$request_uri;
    }

    location / { .... localhost:8000

我能够通过使用 NGINX 的服务器匹配逻辑和正则表达式来解决案例 1-4。

Nginx 将按此顺序解析服务器名称(注意:Nginx 也针对此顺序进行了优化,正则表达式最慢):

  1. 完全匹配
  2. 领先 *
  3. 尾随 *
  4. 第一个正则表达式匹配

这是在下面的代码中实现的匹配和重定向逻辑:

多级子域 ---> 到单级子域 --> 到 ssl

仍然无法在不触发浏览器安全警告的情况下解决 5 和 6(firefox 和 safari 不会抛出这些错误),因为我的通配符 ssl 证书仅对 *.example.com 有效。根本没有办法解决这个问题。

  1. http://sub1.example.com
  2. http://sub2.sub1.example.com
  3. http://sub3.sub2.sub1.example.com
  4. https://sub1.example.com
  5. https://sub2.sub1.example.com
  6. https://sub3.sub2.sub1.example.com

------> https://sub1.example.com

# Default server configuration
server {
    listen 80;
    listen [::]:80;
    listen 443;
    listen [::]:443;
    server_name ~^(.*)\.(?<subdomain>\w+).example\.com$;
    return          301 http://$subdomain.example.com$request_uri; 
}

server {
    listen 80;
    listen [::]:80;
    server_name ~^(?<subdomain>\w+).example\.com$;
    return          301 https://$subdomain.example.com$request_uri; 
}


server {    
    # SSL configuration
    #
    listen 443 ssl default_server;
    listen [::]:443 ssl default_server;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    #
    root /var/www/html; 
    
    location / { ..... localhost:3000