【问题标题】:Nginx use subdomain as query parameter and rewrite URLNginx 使用子域作为查询参数并重写 URL
【发布时间】:2019-02-07 09:00:14
【问题描述】:

我正在尝试使用子域作为域本身的查询参数。 一个例子如下:

我想让 nginx 带上 ab.example.com 并调用 example.com?key=ab,现在后端会返回一个特定的配置,应该使用对于子域“ab”。

之后,用户应该会看到 example.com?key=ab 的内容(准确地说是徽标品牌),但在客户端的 URL 字段中是 ab.example.com 应该坚持下去。

所有进一步的请求都应该显示例如 ab.example.com/login 而不是 example.com/login

我希望我所说的可以充分理解。我尝试了互联网上的各种示例,并试图找到一些提示。

nginx 文件长这样:

server {
    listen 80;
    listen [::]:80;

    server_name www.example.com *.example.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    server_name www.example.com *.example.com;
    ssl_certificate /path/to/certs/ssl.crt;
    ssl_certificate_key /path/to/keys/ssl.key;

    root /var/www/example_site;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html;

    location / {
        try_files $uri $uri/ /index.html =404;
        error_page 404 =200;
    }
}

我已经尝试映射,但它重定向到错误的域:

map $host $subdomain {
    ~^(?<sub>.+)\.example\.com$ $sub;
}

并尝试在服务器块中添加静态 if 语句:

if ($host = "ab.example.com") {
    rewrite . ?key=ab;
}

额外的服务器块也没有帮助:

server {
    listen 80;
    listen [::]:80;
    server_name www.ab.example.come ab.example.com;
    rewrite ^ https://example.com/?key=ab permanent;
}

有没有人看到我做错了什么或者我应该重新阅读文档的哪一部分?

【问题讨论】:

    标签: nginx subdomain


    【解决方案1】:

    您只需在自己的 server_name 指令中执行此操作。您可以直接在那里分配正则表达式中的变量。如果您需要 www. 子域的不同行为,只需从块中删除 *.example.com 并将其添加到另一个文件中:

    server {
        listen       80;
        server_name  ~^(?<subdomain>.+)\.example\.com$; 
        return       301 http://example.com$request_uri?key=$subdomain;
    }
    

    请注意,我没有使用 rewrite,您不应该使用它。使用returnperforms better301 代表重定向类型。然后,您使用您的 server_name 分配的变量来重定向您需要的位置。

    【讨论】:

    • 使用return 301 https://$host$request_uri?key=$subdomain;而不是return 301 http://example.com$request_uri?key=$subdomain; 有效。但是为了让它在重定向到 https 后重新加载保存,需要在 https 服务器块中放置一些逻辑,对吗?
    • 当然!如果您也在为此苦苦挣扎,请打开另一个问题并将其链接到评论中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-05
    • 1970-01-01
    • 2017-11-13
    • 1970-01-01
    相关资源
    最近更新 更多