NGINX使用查询参数重写为文件

问题描述 投票:1回答:1

我希望nginx将url重写为特定的php文件,这些文件可以在第一个斜杠之前由内容确定

例如:

  1. testing.com/testtest.com/test将改写为test.php
  2. testing.com/test2/variable/another-variable将改写为/test2.php?q=variable/another-variable

然后我会使用PHP来爆炸q GET参数。

我目前尝试的是:

location / {
    try_files $uri $uri/ $uri.html $uri.php$is_args$query_string;
}

这适用于上面显示的示例1,但返回404,例如2,其中包含更复杂的URL。

nginx nginx-location
1个回答
1
投票

您可以使用带有location指令的命名try_files来实现一个或多个rewrite语句。有关详细信息,请参阅this document

例如:

location / {
    try_files $uri $uri/ $uri.html @php;
}
location @php {
    rewrite ^(/[^/]+)$ $1.php last;
    rewrite ^(/[^/]+)/(.*)$ $1.php?q=$2 last;
}
location ~ \.php$ {
    try_files $uri =404;
    ...
}

rewrite语句按顺序进行评估。第二个try_files语句确保PHP文件实际存在并且避免使用passing uncontrolled requests to PHP

© www.soinside.com 2019 - 2024. All rights reserved.