NGINX动态位置以创建动态og:image

问题描述 投票:1回答:1

我开发了一个网站,展示了商店中的一些产品。网站网址如下所示:

http://testsite.com

该网站具有共享产品的功能(已经在运行),生成可以在facebook或WhatsApp或任何地方共享的链接。共享产品的链接是:

http://testsite.com/product/1234

其中1234是产品ID。所有产品都有带有ID名称的图像。例如:1234.jpg。产品ID 1234的图像的链接是:

http://testsite.com/static/imgs/1234.jpg

此站点使用简单的NGINX服务器托管,仅提供文件。

在index.html文件的开头,我有一个默认的og:image用于共享:

<meta property="og:image" content="http://testsite.com/static/imgs/main.jpg">

我想NGINX服务器用共享ID图像替换默认的og:image。我已经在NGINX知道如何做到这一点。在NGINX配置文件(/etc/nginx/conf.d/default.conf)中,我使用了sub_filter选项。我的NGINX配置文件是:

server {
    listen       80;
    server_name *.testsite.com;
    root   /var/www/testsite.com/dist;

    location / {
        try_files $uri $uri/ /index.html;
        index  index.html index.htm;
    }

    location ~ /product/(.*) {
        index  index.html index.htm;

        try_files $uri $uri/ /index.html;

        sub_filter 'http://testsite.com/static/imgs/main.jpg'
        'http://testsite.com/static/imgs/$1.jpg';
        sub_filter_once on;
    }
}

此配置适用于位置/,但不适用于位置〜/ product /(。*)

当我使用任何其他图像在location /处测试sub_fiter选项时,它将正确替换。

问题:

1]如何从URL(http://testsite.com/product/1234)获取产品ID(1234)? $ 1不起作用。

2)我认为在位置〜/ product /(。*)处输入时,它还会重定向到位置/。如何修复此配置文件以使其按预期工作?

html nginx facebook-opengraph opengraph nginx-location
1个回答
0
投票

我认为您的alias陈述是问题。在Nginx文档中阅读:

位置/ i / {别名/ data / w3 / images /;}

根据“ /i/top.gif”的请求,将发送文件/data/w3/images/top.gif。

这意味着在您的情况下,每个~/product/(.*)请求都将发送/var/www/testsite.com/dist/index.html,而不会考虑产品ID。您可能需要在/上配置别名以避免这种情况。这也可能是您“重定向”到/的原因。

至于$ 1,它应该可以像现在一样工作。修复alias时,我认为它会起作用。如果不是,则可以尝试命名的匹配:(?<product>[0-9]+)而不是(.*),然后可以使用$product变量来引用ID。

您的代码中还有一个小故障-您在替换时添加了额外的引号。 sub_filter的第二个参数用引号引起来两次。


工作示例

更新:好的,我通过以下nginx配置(在“ Hello World”上测试)在本地主机上工作:

        location ~ /product/(\d+)$ {
                set $product $1;
                try_files $uri $uri/ /index.html;
        }

        location / {
                if ( $product = '' ) {
                   set $search 'Non-Existent-String';
                }
                if ( $product != '' ) {
                   set $search 'World'; # the string you want to replace
                }

                index index.html index.htm;
                sub_filter '$search' 'Product #$product';
        }

这里的关键是,当您使用try_files时,它确实会到达location /。因此,我们需要在/中使用sub_filter。我们也不想sub_filter常规的/index.html请求。像if ($product) sub_filter这样的东西会很好,但是对于nginx来说是不可能的。因此,我只剩下sub_filter,但只为产品请求设置了实际的搜索字符串。

Example

© www.soinside.com 2019 - 2024. All rights reserved.