Apache redirect rule based on a pattern

Viewed 17

I have a virtualhost where I want to redirect all requests that start with a subdomain

*.admin.example.com

to

*-admin.example.com

Basically just replace the Dot with a Dash, and maintain URL path, parameters etc.

1 Answers

You basically want to convert a sub-subdomain to a hyphenated subdomain, ie. <sub-subdomain>.admin.example.com to <sub-subdomain>-admin.example.com.

You can do this using mod_rewrite directly inside your <VirtualHost> container:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^([^.]+)\.(admin\.example\.com) [NC]
RewriteRule ^ https://%1-%2%{REQUEST_URI} [R=302,L]

The above with redirect a request of the form https://<sub-subdomain>.admin.example.com/url-path?params to https://<sub-subdomain>-admin.example.com/url-path?params. The URL-path and any params on the original request are preserved through the redirect.

The %1 and %2 backreferences contain the captured subgroups from the preceding CondPattern, ie. the <sub-subdomain> and rest of the domain after the first dot respectively.

The REQUEST_URI server variable contains the full URL-path, including the slash prefix.

Any query string is passed through by default.

Note that this is a 302 (temporary) redirect. Change this to 301 (permanent) if that is the intention, but only once you have confirmed this works as intended - to avoid potential caching issues.

Related