2015-04-25 175 views
1

我在正確的.htaccess問題上停留在我寧靜的webapp中。我的REST api代碼應該可以通過URL模式*/api/**訪問,它應該被重定向到index.phpapi文件夾中。Apache mod_rewrite Restful api

所有其他URL(靜態文件除外)應重定向到根文件夾中的index.html

我有以下文件夾結構:

 
- api 
-- application/... 
-- vendor/... 
-- index.php 
- public 
-- css/... 
-- js/... 
- index.html 
- .htaccess 

,這是我的.htaccess內容:

Options +FollowSymLinks 
RewriteEngine on 

# redirect all api calls to /api/index.php 
RewriteCond "%{REQUEST_URI}" "^/api" 
RewriteRule "^/api/(.+)$" "/api/index.php$" [QSA,L] 

# If the request is a file, folder or symlink that exists, serve it up 
RewriteCond %{REQUEST_FILENAME} -f [OR] 
RewriteCond %{REQUEST_FILENAME} -d 
RewriteRule ^(.+)$ - [S=1] 

# otherwise, serve your index.html app 
RewriteRule ^(.+)$ /index.html [L] 

我嘗試另一個的.htaccess添加到API文件夾重定向與網址/ api/*但沒有任何成功。所以我試圖用上面的.htaccess中的規則重定向它。

我認爲規則可能是正確的。因爲重定向工作正常。但是/ api /規則不起作用。看來這些請求也被重定向到index.html

我錯過了什麼?

+0

刪除'$'從得到的路徑 – Deadooshka

回答

2

你的正則表達式模式的一些小改動就是你需要:

DirectoryIndex index.php index.html 
Options +FollowSymLinks 
RewriteEngine on 

# redirect all api calls to /api/index.php 
RewriteRule ^api/((?!index\.php$).+)$ api/index.php [L,NC] 

# If the request is a file, folder or symlink that exists, serve it up 
RewriteCond %{REQUEST_FILENAME} -f [OR] 
RewriteCond %{REQUEST_FILENAME} -d 
RewriteRule^- [L] 

# otherwise, serve your index.html app 
RewriteRule ^(.+)$ index.html [L] 
+1

謝謝。它的作品像一個魅力:) –

+1

對不起,以爲我接受它,但只是標記爲有用;) –

+0

沒有問題,很高興它爲你工作。 – anubhava

1

試試下面的設置規則:

Options +FollowSymLinks 
RewriteEngine On 

RewriteCond %{REQUEST_URI} !^/api/index\.php$ [NC] 
RewriteCond %{REQUEST_URI} ^/api [NC] 
RewriteRule ^api/.* /api/index.php$ [QSA,L] 

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-l # to check for symbolic links 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule .* /index.html [L] 

RewriteRule . - [L]