且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 NGINX 重写 URL

更新时间:2023-02-24 12:52:00

我认为问题是缺少美元 $ 来关闭正则表达式字符串,您无论如何都可以将规则重写如下:>

I think the problem is the missing dollar $ to close the regex string, you can anyhow rewrite your rule as following:

location /post/ {
    rewrite ^/post/([\w-]+)-(\d+)$ /post.php?url=$1&id=$2;
}

地点:

  • \w 等价于 [a-zA-Z0-9_] (如果你喜欢去掉 unescore _ 在扩展中重写它版本)
  • \d[0-9]
  • \w is equivalent to [a-zA-Z0-9_] (if you prefer remove unescore _ rewrite it in the extended version)
  • \d is [0-9]

注意:如果你使用~*,它是一个不区分大小写的匹配(不需要双A-Za-z).

NOTE: if you use ~* it's a case insensitive match (the double A-Za-z is not needed).

更新:如果我正确理解你需要什么,我们必须重写规则来做相反的事情(向 post.php?url={kebab-title}&id={id-number} 并实际获取``post/{kebab-title}-{id-number}

UPDATE: if i understand correctly what do you need, we have to rewrite the rule to do the opposite (make a request to post.php?url={kebab-title}&id={id-number} and actually obtain the url of ``post/{kebab-title}-{id-number}

location ~ ^/post\.php\?url=(.*)&id=(\d*)$ {
    alias /post/$1-$2;
}

更新 2为了避免 /post/ 下不需要的匹配,您还可以使用此替代(更具体)版本:

UPDATE 2 to avoid unwanted matches under /post/ you can also use this alternative (more specific) version:

location ~ ^/post/((?:\w+-)+\w+)-(\d+)$ {
    rewrite /post.php?url=$1&id=$2;
}