我在我的 restful web 应用程序中遇到了正确的 .htaccess 问题。我的 REST api 代码应该可以通过 URL 模式 */api/** 访问,它应该被重定向到 api 文件夹中的 index.php。
所有其他 URL(静态文件除外)应重定向到根文件夹中的 index.html。
我有以下文件夹结构:
- api -- application/... -- vendor/... -- index.php - public -- css/... -- js/... - index.html - .htaccess
And this is my .htaccess content:
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/* 重定向 URL,但没有成功。所以我试图用上面的 .htaccess 中的规则重定向它。
我认为下面的规则可能是正确的。因为重定向按预期工作。但是/api/规则不起作用。似乎请求也重定向到 index.html
我错过了什么?
最佳答案
您需要对正则表达式模式进行细微调整:
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]
关于Apache mod_rewrite Restful api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29871378/