Apache mod_rewrite Restful api

标签 apache .htaccess mod-rewrite

我在我的 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/

相关文章:

apache - RewriteCond 以任意顺序匹配查询字符串参数

java - Apache FTP 服务器 - 以编程方式创建用户

.htaccess - htaccess 重定向域,除了一个子域

php - $_FILES 为空,$_POST 为空数组

php - 从 CodeIgniter 3 中的 url 中删除 index.php

apache - 具有多参数的 htaccess

java - 如何在 Java 中更改 Apache POI 中的 XWPFTableCell 边距?

apache - Socket.io 通过 apache 服务器聊天(也运行 php 主站点)

java - Scala Lift - 将文件保存到 apache 中的目录

php - Mod_rewrite,试图排除图像和 css 文件