Nginx 重写规则(使用 try_files?) filename.php?text=$args (to)foldername/?text=$args

标签 nginx url-rewriting

当我使用此请求发送参数 example.com/index.php?text=s1&sort=s2 时,如何在 nginx 中重写规则,但我希望 nginx 将其处理为example.com/process/?text=s1&sort=s2 ?

“s1”和“s2”是您在搜索表单中输入的内容。

我已经尝试过这个:

rewrite ^/index.php?text=(.*)$ /process/?text=$1 last;

还有这个:

location ~* /index.php?text=(.*)$ {
try_files $uri /search/?text=$1;
#try_files $uri /search/?text=$is_args$args;
}

还有这个..

location =index.php?text=$1&sort=$2 {
rewrite index.php?text=$1&sort=$2 /process/text=$1&sort=$2;
}

但不知怎么的,它不起作用。

这是我的配置的主要部分:

location / {
try_files $uri $uri/ /index.php?$query_string;
}

location ~* \.php$ {
include /etc/nginx/php_params;
include /etc/nginx/fastcgi_params;
}

我很困惑..:/

最佳答案

? 之后的任何内容都是查询字符串的一部分,并且可以使用以 arg_ 前缀开头的变量名称来访问各个值。

可以使用以下方式定义所有 /index.php 的简单重写:

location = /index.php {
    rewrite ^ /process/?text=$arg_q&sort=$arg_sort? last;
}

最后的 ? 会阻止 rewrite 将旧查询字符串附加到新 URI 的末尾。

如果您希望仅选出那些包含 $arg_q 参数的 URI,则需要使用 evil if PHP 位置 block 内。像这样:

location ~* \.php$ {    
    if ($arg_q) {
        rewrite ^/index.php$ /process/?text=$arg_q&sort=$arg_sort? last;
    }
    ...
}

编辑:

1) 在您的情况下,URI 主要由 /index.php 处理,但使用 $request_uri 的值(请求的原始值)将其路由到 /index.php 中。如果不执行外部重定向,$request_uri 的值很难修改。

2) 当 /index.php 作为原始请求出现时,您希望将其路由到 /search/$request_uri 的当前值以 /index.php 开头,这是没有帮助的。

解决方案是识别无用的 $request_uri 值,并执行外部重定向来修改 $request_uri 的值。像这样的事情:

if ($request_uri ~ ^/index.php) {
    return 302 /search/?$args;
}
location / {
    try_files $uri $uri/ /index.php?$query_string;
}
location ~* \.php$ {
    ...
}

如果查询字符串相同,只需使用 $args (或 $query_string)附加它。否则将其分解为单独的参数,如我原来的答案所示。

关于Nginx 重写规则(使用 try_files?) filename.php?text=$args (to)foldername/?text=$args,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34953985/

相关文章:

string - 在 Go 中替换 URL 中的协议(protocol)和主机名

node.js - 当我拥有 Kubernetes 时,nginx 的意义何在?

php - 无法在 RHEL + nginx 上解释 PHP

ruby-on-rails - Nginx 和 passenger root 指令不适用于 Capistrano 3。当前版本的符号链接(symbolic link)中断应用程序

php - 在nginx上获取带下划线的标题

redirect - 在 Nginx 中使用参数进行 URL 重定向

ssl - 在 nginx 上游使用 ssl 的 proxy_pass

JavaScript:即使通过 htaccess 隐藏文件扩展名,我也可以获得文件扩展名吗

regex - .htaccess : Removing unwanted symbols from the end of the URL

c# - 如何在运行时在 ASP.Net Core 中创建 url 重写?