Imnl
Imnl

Reputation: 456

How to rewrite a subdomain in htaccess

Im trying to simplify the subdomain complexity perception to the user so I would like to mask the subdomain.

My goal is the following:

When the user tries to get here

blog.example.com/blog/whatever

I would like to mask the subdomain to be

example.com/blog/whatever

Same content served but with the subdomain hidden.

I have tried the following but with no success.

<IfModule mod_rewrite.c>
  RewriteCond %{HTTP_HOST} ^https://blog\.example.com\/blog [NC]
  RewriteRule ^(.*)$ http://example.com/blog/$1 [R=301,L]
</IfModule>

Update: Rewrite module is enabled

Upvotes: 1

Views: 51

Answers (1)

MrWhite
MrWhite

Reputation: 45829

RewriteCond %{HTTP_HOST} ^https://blog\.example.com\/blog [NC]
RewriteRule ^(.*)$ http://example.com/blog/$1 [R=301,L]

The HTTP Host header (ie. the value of the HTTP_HOST server variable) contains the hostname only, ie. blog.example.com. It does not contain the full absolute URL.

So, your rule should be like this instead:

RewriteCond %{HTTP_HOST} ^blog\.example\.com [NC]
RewriteRule ^blog($|/) https://example.com%{REQUEST_URI} [R=301,L]

This matches the URL-path /blog or /blog/<whatever> (but not /blog<something>) and redirects to the same URL-path at example.com (+ HTTPS). The REQUEST_URI server variable contains the root-relative URL-path, starting with a slash.

You were redirecting to HTTP, but I assume this must be HTTPS?

You should clear your browser cache before testing and test first with a 302 (temporary) redirect to avoid potential caching issues.

Upvotes: 1

Related Questions