简体   繁体   English

.htaccess 规则重定向到默认 API 版本

[英].htaccess rule to redirect to default API version

In my PHP API, I would like to redirect requests that don't include a version number to a default version.在我的 PHP API 中,我想将不包含版本号的请求重定向到默认版本。

So for example, a request to例如,一个请求

/api/<endpoint>

will redirect to将重定向到

/api/v2/<endpoint>

if v2 is the default version for the API.如果 v2 是 API 的默认版本。 Requests that include a version number should work as normal.包含版本号的请求应该正常工作。

The file structure is like this:文件结构是这样的:

  • api api
    • v1 v1
    • v2 v2
      • (endpoints) (端点)

I'm struggling to understand the .htaccess syntax, and what Apache expression is required.我很难理解 .htaccess 语法,以及需要什么 Apache 表达式。 What I've tried so far is to check if the URL contains a version number in it:到目前为止,我尝试的是检查 URL 中是否包含版本号:

RewriteEngine On

# Redirect requests from /api/ to current version of the API
RewriteCond %{DOCUMENT_ROOT} !^(v[0-9])$
RewriteRule ^?$ /v1/$1

Does anyone have experience with this issue or know how to go about solving it?有没有人有这个问题的经验或知道如何解决这个问题?

I'm assuming you mean an internal rewrite, as opposed to an external 3xx "redirect"?我假设您的意思是内部重写,而不是外部 3xx“重定向”?

You could do something like the following using mod_rewrite in your root .htaccess file:您可以在根.htaccess文件中使用 mod_rewrite 执行以下操作:

# Set env var to default API version
SetEnvIf ^ ^ DEFAULT_API_VERSION=2

# Rewrite requests from /api/ to default version of the API if not explicitly set
RewriteRule ^api/(?!v\d+/)(.*) /api/v${ENV:DEFAULT_API_VERSION}/$1 [L]

The environment variable is just a convenience to avoid having to modify the later rule.环境变量只是为了方便避免修改后面的规则。

The complete "version" path segment is assumed to be v followed by any number of digits, followed by a slash.完整的“版本”路径段假定为v后跟任意数量的数字,后跟斜杠。

This uses a negative lookahead to avoid matching URLs that already contain a version string as the second path segment.这使用负前瞻来避免匹配已经包含版本字符串作为第二个路径段的 URL。 Otherwise the URL-path after /api/ is captured in the $1 backreference and used in the substitution string.否则/api/之后的 URL 路径将在$1反向引用中捕获并用于替换字符串。

The above will rewrite as follows:上面将重写如下:

  • /api/v1/<endpoint> - no change /api/v1/<endpoint> - 没有变化
  • /api/<endpoint> - rewrite to /api/v2/<endpoint> /api/<endpoint> - 重写为/api/v2/<endpoint>
  • /api/ - rewrite to /api/v2/ /api/ - 重写为/api/v2/
  • /api/v1234/ - no change /api/v1234/ - 没有变化
  • /api/v1234 (no trailing slash) - rewrite to /api/v2/v1234 /api/v1234 (无斜杠) - 重写为/api/v2/v1234
  • /api/v2.1234/foo - rewrite to /api/v2/v2.1234/foo /api/v2.1234/foo - 重写为/api/v2/v2.1234/foo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM