【问题标题】:nginx rewrite slug to querystring without changing urlnginx 将 slug 重写为查询字符串而不更改 url
【发布时间】:2021-09-17 12:56:57
【问题描述】:

我需要在不更改浏览器 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;

他们都 REDIRECT 到 url 的查询字符串版本,“works”但不是我想要的。我不想更改浏览器中的网址。

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

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

即使那是被请求的资源。

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

此服务器正在使用: Plesk 黑曜石 18.0.36 Nginx 1.20.1

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

谢谢!

【问题讨论】:

    标签: nginx url-rewriting


    【解决方案1】:

    这两个rewrite 指令都不应导致重定向,而应导致内部 URI 重写。此重定向可能是由您的后端生成的。如果您的后端是 PHP 应用程序,您可以尝试更改 REQUEST_URI PHP-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;
        ...
    }
    

    阅读this答案的第一部分了解更多详情。

    【讨论】:

    • 这就是我从阅读中想到的,但它重定向而不是重写。该站点是静态 html,带有 javascript 获取数据,甚至没有为该域启用 php。此服务器正在使用:Plesk Obsidian 18.0.36 Nginx 1.20.1 我已经用这些细节更新了问题。我应该尝试添加吗?还是我遇到了不同的问题?感谢您的帮助!
    猜你喜欢
    • 2012-10-08
    • 2013-02-25
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 2016-11-17
    相关资源
    最近更新 更多