简体   繁体   English

NGINX 多域动态重定向

[英]NGINX dynamic redirect with multiple domains

Use case用例

Our current frontend app was accessible by multiple domains:我们当前的前端应用程序可以被多个域访问:

https://boat.com (or https://www.boat.com)
https://car.com
https://plane.com
...

Each domain, was rendering the same app with different content and theme based on the domain name.每个域都根据域名呈现具有不同内容和主题的相同应用程序。

We are now trying to merge everything under one unique domain.我们现在正试图将所有内容合并到一个独特的域下。 So instead of accessing the site using its previous domain:因此,不要使用以前的域访问该站点:

https://car.com

we want to access it using the following url:我们想使用以下 url 访问它:

https://common.com/car

On the code, we already took care of changing the logic to deliver the correct content based on this new routing system.在代码上,我们已经处理了更改逻辑以基于这个新的路由系统提供正确的内容。

Problem问题

We want to redirect automatically our users to the correct routes when they try to access the app from an old domain.当用户尝试从旧域访问应用程序时,我们希望自动将用户重定向到正确的路由。 Example:例子:

https://boat.com      => redirect => https://common.com/boat
https://car.com       => redirect => https://common.com/car
...

but we also want to be able to rewrite more complex url:但我们也希望能够重写更复杂的 url:

https://boat.com/categories/name-1     => redirect => https://common.com/boat/categories/name-1
https://car.com/posts/super-title-2    => redirect => https://common.com/car/posts/super-title-2

Is there a way to achieve it using NGINX dynamically/programmatically without having to write and repeat rules for each domains?有没有办法以动态/编程方式使用 NGINX 来实现它,而无需为每个域编写和重复规则?

You can obtain the domain name by using a regular expression server_name .您可以使用正则表达式server_name获取域名。

For example:例如:

server {
    listen 80;
    listen 443 ssl;

    ssl_certificate     /path/to/$ssl_server_name.crt;
    ssl_certificate_key /path/to/$ssl_server_name.key;

    server_name   ~^(www\.)?(?<domain>[^.]+)\.com$;
    return 301 https://example.com/$domain$request_uri;
}

The problem will be selecting the correct SSL certificate for each of the deprecated domains.问题将是为每个已弃用的域选择正确的 SSL 证书。 Nginx has limited capability for selecting certificates dynamically which involves using the $ssl_server_name variable. Nginx 动态选择证书的能力有限,这涉及使用$ssl_server_name变量。 This means that you will need a directory containing all possible certificate combinations, even if some of those files are identical.这意味着您将需要一个包含所有可能的证书组合的目录,即使其中一些文件是相同的。

For example:例如:

boat.com.crt
boat.com.key
www.boat.com.crt
www.boat.com.key
car.com.crt
car.com.key
www.car.com.crt
www.car.com.key

Also, you should define a default server, as you do not want this server block to be your default server.此外,您应该定义一个默认服务器,因为您不希望此服务器块成为您的默认服务器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM