【问题标题】:Apache mod_rewrite Restful apiApache mod_rewrite Restful api
【发布时间】:2015-07-04 11:13:56
【问题描述】:

我在我的安静的 web 应用程序中遇到了正确的 .htaccess 问题。我的 REST api 代码应可通过 URL 模式 */api/** 访问,该 URL 模式应重定向到 api 文件夹中的 index.php

所有其他 URL(静态文件除外)应重定向到根文件夹中的 index.html

我有以下文件夹结构:

- api - 应用/... - 小贩/... -- 索引.php - 民众 --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/* 重定向 URL,但没有任何成功。所以我尝试使用上面 .htaccess 中的规则重定向它。

我认为较低的规则可能是正确的。因为重定向按预期工作。但是 /api/ 规则不起作用。似乎请求也重定向到了 index.html

我错过了什么?

【问题讨论】:

  • 从结果路径中删除 $
  • 我在 Rest API 中有一些问题,如果我尝试 -> abc.com/api/rest/products?limit=2 我的网站返回 404 页面错误,我该如何解决这个问题,我该如何解决使用 REST API @Georg Leber 获取产品
  • @Rathinam 请在 SO 上创建一个新问题,以更详细地显示您的问题。这可能有几个问题,无法在 cmets 中讨论(例如,服务器端映射如何......)
  • @GeorgLeber ye,已经有人发帖了——> magento.stackexchange.com/q/246597/57334

标签: apache .htaccess mod-rewrite


【解决方案1】:

您需要对正则表达式模式进行细微调整:

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]

【讨论】:

  • 这也适用于我的情况,我的引导 PHP 文件包含在 /api 文件夹中,但我一直在努力让重写正确。我开始认为DirectoryIndex 并明确地希望在 API 重写中匹配 index.php 是这里的秘诀。谢谢!
  • @anubhava 我在 Rest API 中有一些问题,如果我尝试 -> abc.com/api/rest/products?limit=2 我的网站返回 404 页面错误,我该如何解决这个问题以及如何解决我可以使用 REST API 获取产品吗?
  • 有人已经过去了,你能帮忙吗magento.stackexchange.com/q/246597/57334
  • @anubhava zus 更新了问题,比如我需要什么,你能帮我吗?
  • @Rathinam:看起来这是一个 magento 配置问题,而不是 mod_rewrite 问题。不幸的是,我对 magento 知之甚少。
【解决方案2】:

尝试以下规则:

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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多