【问题标题】:nginx rewrite if specific name is included如果包含特定名称,则 nginx 重写
【发布时间】:2014-08-24 17:02:27
【问题描述】:

我想将所有包含“xhr.php”的请求重写为/xhr.php,而不是原来的路径。

请求:

type: "POST",
url: "/system/classes/templates/address/xhr.getAddress.php",
data: vars,
dataType: "html"

应该以路径作为参数转到 /xhr.php。我试过这个:

 rewrite ^/(.*)/xhr.(.*)\.php$ /xhr.php?parameter=$1&parameter2=$2 last;

但是它不起作用。有任何想法吗?我的配置如下所示:

location / {
    root  /var/www/http;
    try_files $uri $uri/ index.php /index.php$is_args$args @rewrite;
}

location @rewrite {
    rewrite ^/(.*)/xhr.(.*)\.php$ /xhr.php?parameter=$1&parameter2=$2 last;
}

这基本上可以用 nginx 实现吗?这里有什么问题? 谢谢:)

//编辑: 我解决了,但是看起来效率不高……

location / {
  root  /var/www/http;
  try_files $uri $uri/ index.php /index.php$is_args$args;
}

if ($request_uri ~ .*/xhr.*) {
   rewrite ^/(.*)/xhr.(.*)\.php$ /xhr.php?parameter=$1&parameter2=$2 break;
}

【问题讨论】:

    标签: nginx rewrite


    【解决方案1】:

    您可以删除 if 并让重写在同一级别的位置。这样,您将为每个请求保存一个正则表达式(if 中的那个)。

    其实我觉得你也可以去掉location /

    root /var/www/http;
    rewrite ^/(.*)/xhr.(.*)\.php$ /xhr.php?parameter=$1&parameter2=$2 break;
    try_files $uri $uri/ index.php /index.php$is_args$args;
    

    【讨论】:

    • 仅在没有位置 / 的情况下有效 - 但是它有效!
    • 好!出于好奇:您是否尝试过将重写放在位置 / 之前?
    • 不,还没有。不过我明天试试。
    猜你喜欢
    • 1970-01-01
    • 2016-12-26
    • 2014-10-10
    • 2020-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    相关资源
    最近更新 更多