nginx - 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
希望这是有道理的。任何帮助将不胜感激。
谢谢!
解决方案
这两个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;
...
}
阅读此答案的第一部分以获取更多详细信息。
推荐阅读
- swift - CoreML 是否可以与 swift 包管理器一起使用?
- ios - 检查单元格是否完全显示在collectionview中
- php - laravel-graphql php artisan 命令'无法打开输入文件:make:graphql:type'
- java - Java登录系统不工作;读取第一个用户,但无法解析第二个或下一个用户
- ionic-framework - 将 Ionic 中的标签名称更改为居中文本后如何重新加载标签页?
- php - 如果数字已被猜到,如何将信息从两个会话变量发送到文本文件
- azure - Service Fabric 可靠的参与者和 I/O 操作
- list - 如何在 prolog 中打印出我的事实列表?
- design-patterns - 具有指定要运行的任务类型的字段的对象是否有设计模式?
- javascript - 使用角度 4 将一个数组列表中的项目组合插入另一个数组列表