在NGINX中重定向和重写

时间:2014-03-31 10:32:19

标签: redirect nginx webserver rewrite

我正在尝试创建一个简单的" Hello World" -like API,为此,我需要一个规则来将URL重定向/重写到我的API。

我们假设我的文件名为index.php,因此每当我GET index.php时,我都会得到items的列表。

我要做的第一件事就是将网址mydomain.com/index.php重定向到mydomain.com/api

第二,访问mydomain.com/api时,我希望服务器在不重写URL的情况下触发index.php文件。

我目前的代码如下:

location /api {
    rewrite ^ $scheme://$host/index.php permanent;
}

location /index.php{
    return 302 www.mydomain.com/api;
}

但它没有按预期工作。为什么以及如何解决?

2 个答案:

答案 0 :(得分:0)

# you don't need a rewrite. Use location with the "=" or exact match
location = /api {
    alias /path/to/root;
    index index.php;
}

location /index.php {
    return 302 www.mydomain.com/api;
}

希望有所帮助

以下是使用一个重定向和别名的答案的第二个版本:

   location /api {                                
     alias /path/to/root;                       
     index index.php;                             
   }                                              

   # replace index.php with api                   
   location /index.php {                          
     rewrite (index\.php)(.*)$ /api$2 permanent;  
   }                                              

我的第一个解决方案没有转发args。阅读@alexandernst解决方案可以更好地了解问题。

答案 1 :(得分:0)

您需要遵守两条规则。

第一个,即接收请求的那个,"翻译"它们是你的引擎脚本,应该是这样的:

rewrite ^/api\?(.+)$ /index.php?$1 last;

至于第二个,应该将所有用户重定向到" beautiful"网址:

rewrite  ^/index.php\?(.*)$    /api?$1    permanent;

请注意,第二条规则应之外任何位置区块之前其中任何一条区域,因为您愿意在之前重定向用户 / b>其他任何事情。

干杯