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

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

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 /(.*)

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

问题:

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

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

minuteslove 回答:NGINX动态位置创建动态og:image

我认为您的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

本文链接:https://www.f2er.com/3155823.html

大家都在问