Apache 2.4:我可以在请求中使用条件变量吗



tl;dr

在NGINX中,您可以定义变量并在每个请求中对其进行评估。我不可能在Apache v2.4中重现这一点我可以在请求中使用条件变量吗

我想要什么

${docroot}/dev/api.php包含一个API,该API不应通过直接访问来访问,而只能通过位置/api来访问。

  1. 用户访问CCD_ 3并得到错误404或"0";需要授权">
  2. 用户访问example.org./api/endpoint,它在内部回退到/dev/api.php

在NGINX中,我可以为此使用一个变量。如果用户访问该位置,则变量为TRUE,否则(例如,直接访问(为false,他会得到错误。

代码

<VirtualHost *:8443>
Define docroot /var/www/html/test
Define fromAPI false # default is: no access

ServerName    shop.example.org
ServerAdmin   admin@example.org
DocumentRoot  ${docroot}
Protocols h2 http/1.1

# that's the location of the API (there is no directory named "api")
<Location /api>
AllowOverride None
Define fromAPI true # user has access
FallbackResource /dev/api.php
</Location>

# The API code is living here.
# When user visits it "${fromAPI} == false", it should end up in error 404.
# When API visits it "${fromAPI} == true", the access should be granted.
<Directory ${docroot}/dev>
# <If "-T env('fromAPI')">
# <If "-T env('fromAPI')">
# <If "${fromAPI}">
# <If "-T '${fromAPI}'">
Redirect 404 /dev/
</If>
</Directory>

SSLEngine on
SSLProtocol -all +TLSv1.2 
SSLCertificateFile    /etc/letsencrypt/live/example.org/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/example.org/privkey.pem

# HTTP Strict Transport Security (mod_headers is required) (31536000 seconds)
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
# that's the location of the API (there is no directory named "api")
<Location /api>
AllowOverride None
Define fromAPI true # user has access
FallbackResource /dev/api.php
</Location>
# The API code is living here.
# When user visits it "${fromAPI} == false", it should end up in error 404.
# When API visits it "${fromAPI} == true", the access should be granted.
<Directory ${docroot}/dev>
# <If "-T env('fromAPI')">
# <If "-T env('fromAPI')">
# <If "${fromAPI}">
# <If "-T '${fromAPI}'">
Redirect 404 /dev/
</If>
</Directory>

我不确定这种模式是否有效,因为<Location>节在<Directory>节之后合并

您可以在${docroot}的主<Directory>部分中使用mod_rewrite来完成此操作。

例如:

<Directory ${docroot}>
Require all granted
AllowOverride None
RewriteEngine On
# Block direct access to "/dev/"
RewriteRule ^dev/ - [R=404]
# Rewrite "/api/<something>" to "/dev/api.php"
RewriteRule ^api/. dev/api.php [END]
</Directory>

我使用mod_rewrite,而不是FallbackResource,以便专门针对仅针对/api/<something>的请求。

CCD_ 11标志阻止重写引擎在此上下文中的所有进一步处理。(因此,前面阻止访问的规则不需要阻止重写请求的条件。(

最新更新