2014-03-31 119 views
1

重寫我試圖般的API創建一個簡單的「Hello World」爲此,我需要一個規則來重定向/ URL重寫我的API。重定向和NGINX

比方說,我的文件被稱爲index.php,所以每當我做一個GETindex.php我得到的items列表。

我要做的第一件事就是mydomain.com/index.php重定向的URL 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; 
} 

但預計它不工作。爲什麼以及如何修復它?

回答

0

你需要爲你想達到什麼樣的兩條規則。

第一個,將接收請求和「翻譯」到您的下引擎罩劇本的人,應該是這樣的:

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

至於第二個,一個應該所有用戶重定向到「美麗」的網址:

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

注意這第二條規則應該是任何位置塊和任何這些之前,你願意重定向之前的其他用戶

乾杯

+0

正是我在找什麼!謝謝! – marioshki

+0

有條件和捕獲組有問題。這個?應該在捕獲組之後:重寫^/api(。+)?$ /index.php?$1 last;重寫^/index.php(。*)?$/api?$ 1 permanent; – alfredocambera

+0

@alfredocambera不,實際上它應該放在組之前,因爲它與字面字符''''''匹配,而不是在index.php後面加任何內容。 – alexandernst

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解決方案更好地瞭解了這個問題。

+0

所以,如果我想訪問的index.php書面方式/ API,我必須使用: 位置=/API { 別名/; index index.php; } 它dosent工作..它去/ API /並給我一個404(也許搜索/api/index.php?) – marioshki

+0

什麼ü您的訪問日誌中看到?它在文件系統上尋找哪條路徑? – alfredocambera

+0

當我訪問** www.mydomain.com/API **鉻網絡日誌說我www.mydomain.com/api **永久移動(301)**到www.mydomain.com/api/並拋出* *之後的404錯誤**。 – marioshki