除特定 URI 之外的所有位置的 Apache 配置

Apache config for all Location except specific URI

我需要为位置指令应用一些配置。

这些配置必须应用于所有位置,除了某些 URIs(例如,我不想更改 /products 的配置,因此必须将以下配置应用于所有位置,/产品)

<Location />
 # desired configurations
</Location>

这可以通过多种方式完成:

1。使用 正则表达式

位置指令中使用正则表达式来匹配所有 URI,除了你的模式

例如:

<Location ~ "^((?!/product).)*$">
# desired configurations
</Location>

2。使用 指令

例如:在您的目录中使用 If

<If "%{Request_URI} != '.*/product.*'">

<If "%{Request_URI} != '^((?!/product).)*$'">

3。通过设置变量并使用 If 和 IfDefine

在配置开始时设置一个变量,然后使用指令

SetEnvIf Request_URI ".*/product.*" isProd=1
...
<IfDefine isProd>
...

或者您可以在 If 指令中使用 expr 来比较字符串和变量。

4。通过使用另一个 <Location>

可以通过覆盖之后的 <Location> 部分来更改它。例如,这将对除 /.well-known/ 以外的所有内容强制执行身份验证,这是从 Let's Encrypt:

获取 TLS 证书的常见模式
        <Location />
                AuthType Basic
                AuthName "Restricted Content"
                AuthUserFile /etc/apache2/htpasswd
                Require valid-user
        </Location>
        <Location /.well-known/>
                Require all granted
        </Location>

这将要求用户输入所有 /* 除了 /.well-known/* 不需要密码的密码。

有关这方面的更多信息,请参阅 upstream documentation on configuration sections


Useful link