代码之家  ›  专栏  ›  技术社区  ›  Mithc

Nginx location regex用于处理/sub/目录中多个WordPress站点的永久链接

  •  0
  • Mithc  · 技术社区  · 7 年前

    我正在寻找一个动态解决方案来处理安装在子目录中的多个WordPress站点(节点)的永久链接。

    这些站点可以使用这样的url访问(我使用 cluster node 要表示结构,但每种情况下它们都不同,但它们始终遵循相同的结构,节点是包含WordPress根文件的目录):

    https://www.domain.tld/cluster1/node1/

    location /cluster1/node1/ {
        try_files $uri $uri/ /cluster1/node1/index.php$is_args$args;
    }
    
    location /cluster2/node2/ {
        try_files $uri $uri/ /cluster2/node2/index.php$is_args$args;
    }
    
    location /cluster3/node3/ {
        try_files $uri $uri/ /cluster3/node3/index.php$is_args$args;
    }
    
    location /cluster4/node4/ {
        try_files $uri $uri/ /cluster4/node4/index.php$is_args$args;
    }
    

    可以,但是有超过43个节点(不断变化)。所以,我尝试了以下几点:

    location /([^/]+)/([^/]+)/ {
        try_files $uri $uri/ /$1/$2/index.php$is_args$args;
    }
    

    显示 主页 正确,但是对于节点的页面显示404 https://www.domain.tld/cluster1/node1/page/

    location ~ ^/([^/]+)/([^/]+)/ {
        try_files $uri $uri/ /$1/$2/index.php$is_args$args;
    }
    

    但是这使得PHP文件作为一个名为 download

    location ~ /([^/]+)/([^/]+)/ {
        try_files $uri $uri/ /$1/$2/index.php$is_args$args;
    }
    

    和以前一样。

    location ^~ /([^/]+)/([^/]+)/ {
        try_files $uri $uri/ /$1/$2/index.php$is_args$args;
    }
    

    这使得 主页 该节点的下载与之前的尝试相同,但显示了404的节点页面(如 https://www.domain.tld/cluster1/node1/页面/

    你知道为什么上面这些都不起作用吗?有什么建议让它起作用吗?

    0 回复  |  直到 7 年前
        1
  •  2
  •   Richard Smith    7 年前

    您需要使用正则表达式 location 块捕获内部重定向到正确的 index.php 位置 使用 ~ ~* 修饰语。见 this document

    正则表达式是按顺序计算的,因此 位置 对于 \.php$ 必须 置于 您正在插入。否则,PHP文件将被下载而不是执行。

    例如:

    location ~ \.php$ {
        ...
    }
    location ~ ^/([^/]+)/([^/]+)/ {
        try_files $uri $uri/ /$1/$2/index.php$is_args$args;
    }