Can you set up mod_rewrite for wildcard domains in Apache?

Linode Staff

What's the best way to set up a rewrite to change a subdomain, such as sub.example.com into a page such as example.com/sub?

3 Replies

I'm by no means an expert, but following the official Apache mod_rewrite documentation and examples, it looks like you can accomplish this in one of two ways:

With mod_rewrite:

RewriteEngine on
RewriteRule "^(.*).example.com" "http://example.com/$1" [R,L]

Or with RedirectMatch:

RedirectMatch "^(.*).example.com" "http://example.com/$1"

It may be there's some additional nuances in a specific case that would require different rules or syntax, so I'd recommend reviewing the official documentation when writing any mod_rewrite rules or conditions.

Tried that Woet.
MJones, the problem is I would like to reuse the unknown subdomain. ^(.*).domain2.com in the rewrite of the destination URl. I will at least start with your example, because even a basic redirect isn't working at this point, then go from there. thank you.

Reply

Please enter an answer
Tips:

You can mention users to notify them: @username

You can use Markdown to format your question. For more examples see the Markdown Cheatsheet.

> I’m a blockquote.

I’m a blockquote.

[I'm a link] (https://www.google.com)

I'm a link

**I am bold** I am bold

*I am italicized* I am italicized

Community Code of Conduct