We want to redirect users from an old domain to a new domain defined in an environment variable:

SetEnvIfExpr true SERVER_HOST_NAME=mynewdomain.example

The follwoing works in Apache 2.4 to redirect to a defined host name in an environment variable:

Redirect permanent https://%{env:SERVER_HOST_NAME}/

This however does not:

Redirect permanent / https://%{env:SERVER_HOST_NAME}/

The 2nd option is preferable because it maintains the path so if the request is:

GET https://myOLDdomain.example/somepath

The first option will always redirect the user to:

    GET https://mynewdomain.example/

instead of:

    GET https://mynewdomain.example/somepath

Currently the 2nd option redirects the user (literally) to:

    GET https://%{env:SERVER_HOST_NAME}/somepath

Is it a bug that Apache is not resolving %{env:SERVER_HOST_NAME}?

  • Why not just use Redirect permanent / https://mynewdomain.example/? There is no need to put it in a variable. – Stephen Ostermiller Aug 9 '19 at 9:10
  • We have our reasons: the same apache httpd.conf can be used in different docker containers with different configuration (via environment variables). – Marc Aug 9 '19 at 17:51
  • Did you try with RedirectPermanent instead? And which version of Apache? – Patrick Mevzek Aug 9 '19 at 20:16

The use of an expression, like your %{env:SERVER_HOST_NAME}, at the URL of a <Redirect> is not possible, unless it's placed within a <LocationMatch> for example.

... If the Redirect directive is used within a or section with the URL-path omitted, then the URL parameter will be interpreted using expression syntax. This syntax is available in Apache 2.4.19 and later. ...

See also https://httpd.apache.org/docs/2.4/en/mod/mod_alias.html#redirect

An example of this could look like this:

SetEnvIfExpr true SERVER_HOST_NAME=mynewdomain.example
<LocationMatch "^/(?<REMAINING>.*)">
    Redirect permanent https://%{env:SERVER_HOST_NAME}/%{env:MATCH_REMAINING}

The named group, REMAINING at the <LocationMatch> allows you to append the requested URL path to the URL send with the redirect response. So the client gets redirect to the same URL path but on SERVER_HOST_NAME.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.