首页 > 解决方案 > nginx 将 slug 重写为查询字符串而不更改 url

问题描述

我需要在不更改浏览器 url 的情况下将 slug 重写为 nginx 中的查询字符串。

在 Apache 中,以下工作:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/theblog/([0-9a-zA-Z-]+)$ /theblog/blog?slug=$1 [L,QSA]

在 nginx 中,我尝试了以下两种方法:

rewrite ^\/theblog\/((?!blog?)[^\/]+)$ /theblog/blog?slug=$1 break;

rewrite ^\/theblog\/((?!blog?)[^\/]+)$ /theblog/blog?slug=$1 last;

他们都重定向到 url 的查询字符串版本,它“有效”但不是我想要的。我不想更改浏览器中的网址。

我希望网址保留:http ://example.com/theblog/test

不重定向到:http ://example.com/theblog/blog?slug=test

即使那是被请求的资源。

该站点是静态 html,带有 javascript 获取数据,甚至没有为该域启用 php。

此服务器正在使用:Plesk Obsidian 18.0.36 Nginx 1.20.1

希望这是有道理的。任何帮助将不胜感激。

谢谢!

标签: nginxurl-rewriting

解决方案


这两个rewrite指令都不应该导致重定向,而是导致内部 URI 重写。此重定向可能是由您的后端生成的。如果您的后端是 PHP 应用程序,您可以尝试更改REQUEST_URIPHP-FPM 参数:

rewrite ^\/theblog\/((?!blog?)[^\/]+)$ /theblog/blog?slug=$1 last;

...

location ~ \.php$ {
    ...
    include fastcgi_params;
    # default "fastcgi_params" file contains the following line:
    # fastcgi_param REQUEST_URI $request_uri;
    # now we should overwrite it with a new value:
    fastcgi_param REQUEST_URI $uri$is_args$args;
    ...
}

阅读此答案的第一部分以获取更多详细信息。


推荐阅读