Question

I'm trying to create a simple "Hello World"-like API and for that I need a rule to redirect/rewrite the URL to my API.

Let's say my file is called index.php, so whenever I make a GET to index.php I get a list of items.

The first thing I want to do is to redirect the URL mydomain.com/index.php to mydomain.com/api.

And second, when mydomain.com/api is accessed, I'd like the server to trigger the index.php file without rewriting the URL.

My current code looks like this:

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

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

but it's not working as expected. Why and how can I fix it?

Était-ce utile?

La solution

You need two rules for what you're trying to achieve.

The first one, the one that will receive requests and "translate" them to your under-the-hood script, should look like this:

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

As for the second one, the one that should redirect all your users to the "beautiful" URL:

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

Note that this second rule should be outside any location block and before any of those, as you're willing to redirect the user before anything else.

Cheers

Autres conseils

# 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;
}

Hope it helps

Here is the second version of my answer using one redirect and an alias:

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

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

My first solution did not forwarded the args. Reading @alexandernst solution gave a better idea of the problem.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top