Search code examples
regexlocationapache2configdirective

Apache config for all Location except specific URI


I need to apply some configuration for a Location Directive.

These configurations must be applied for all location, except some URIs (e.g. I don't wanna change configs for /products, so bellow configuration must be applied for all locations, except /products )

<Location />
 # desired configurations
</Location>

Solution

  • This can be done in several ways:

    1. Using regex

    Use regex in Location Directive to match all URIs, except your pattern

    e.g.:

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

    2. Using < If> directive

    e.g.: use If inside your directory:

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

    or

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

    3. By setting variables and using If and IfDefine

    Set a variable at start of configurations, and then use directive

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

    or you can use expr in If directive for comparing strings and variables.

    4. By using another <Location>

    It's possible to change an earlier <Location> section by overriding it after. For example, this will enforce authentication on everything but /.well-known/, a common pattern to get TLS certificates from Let's Encrypt:

            <Location />
                    AuthType Basic
                    AuthName "Restricted Content"
                    AuthUserFile /etc/apache2/htpasswd
                    Require valid-user
            </Location>
            <Location /.well-known/>
                    Require all granted
            </Location>
    

    This will ask users for passwords in all of /* except for /.well-known/* which will not require a password.

    See the upstream documentation on configuration sections for more information on this.


    Useful link