【问题标题】:Redirecting and rewriting in NGINXNGINX 中的重定向和重写
【发布时间】:2014-05-10 15:47:43
【问题描述】:

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

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

我要做的第一件事是将 URL 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;
}

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

【问题讨论】:

    标签: redirect nginx webserver rewrite


    【解决方案1】:
    # 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 解决方案可以更好地了解问题。

    【讨论】:

    • 所以,如果我想访问 /index.php 写入 /api,我必须使用:location = /api{ alias /;索引 index.php; } 它不起作用..它转到 /api/ 并给我一个 404(也许正在搜索 /api/index.php?)
    • 您在访问日志中看到了什么?它在您的文件系统上寻找哪个路径?
    • 当我访问 www.mydomain.com/api chrome 网络日志告诉我 www.mydomain.com/api 永久移动 (301) 到 www.mydomain.com/api/ 并在此之后引发 404 错误
    • 表示该目录下没有index.php。如果您尝试 www.mydomain.com/api/index.php 它应该显示相同的消息。访问日志显示文件系统路径,它试图访问。
    • 我的 api 目录不存在,我想访问根目录中的 index.php,写在 url /api ,反之亦然(编写index.php,将url重写为/api,但留在index.php中)
    【解决方案2】:

    你需要两条规则来实现你想要达到的目标。

    第一个,将接收请求并将其“翻译”为您的底层脚本的那个,应该如下所示:

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

    至于第二个,应该将所有用户重定向到“美丽”的 URL:

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

    请注意,第二条规则应该在任何位置块之外和任何位置块之前,因为您愿意重定向用户之前 还有什么。

    干杯

    【讨论】:

    • 正是我想要的!谢谢!
    • 条件和捕获组有问题。这 ?应该在捕获组之后: rewrite ^/api(.+)?$ /index.php?$1 last;重写 ^/index.php(.*)?$ /api?$1 永久;
    • @alfredocambera 不,实际上它应该放在组之前,因为它匹配文字字符 ?,而不是使 index.php 之后的任何内容可选。
    • @alexandernst 您在第一个表达式上匹配“i”,在第二个表达式上匹配“p”。检查rick.measham.id.au/paste/explain.pl?regex=^%2Fapi%28.%2B%29%3F%24 和rick.measham.id.au/paste/explain.pl?regex=^%2Fapi%3F%28.%2B%29%24
    • @alfredocambera 啊,确实。所以在解析我的答案时擦除了转义字符。立即编辑
    猜你喜欢
    • 1970-01-01
    • 2013-11-05
    • 2016-04-29
    • 1970-01-01
    • 2013-07-12
    • 2013-08-20
    • 2017-04-24
    • 2018-11-11
    • 1970-01-01
    相关资源
    最近更新 更多