Dalv
Dalv

Reputation: 21

.htaccess 301 redirect with an exception

I'm using a reverse proxy to have https://blog.example.com/ show at https://www.example.com/blog/

In order to eliminate infinite loop, I need to set up a 301 redirection from https://blog.example.com/ to https://www.example.com/blog/ with an exception of traffic coming from the main WWW domain.

This seems to work, but it fails to redirect all inner pages, like blog.example.com/folder1/, blog.example.com/folder2/, etc.

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

How can I fix it?

Upvotes: 1

Views: 236

Answers (1)

MrWhite
MrWhite

Reputation: 45914

The "problem" with proxying the request to a particular target URL is that according to the target server, the user is actually making a request to the target URL - that's the point of a reverse proxy.

So, if the user makes a request to https://www.example.com/blog/ which you reverse proxy to https://blog.example.com/ then the target server thinks you are making a request to https://blog.example.com/ - just as if the user had made a direct request to https://blog.example.com/.

So, you can't simply redirect based on the URL being requested.

However, when the request passes through your proxy server then this should be setting various HTTP request headers - passing on information about the actual request the client is making. You could check for the absence of one of these headers - thus indicating a direct request that has not gone through your reverse proxy server.

For example, try the following:

RewriteCond %{HTTP:X-Forwarded-Host} ^$
RewriteCond %{HTTP_HOST} ^(blog)\.example\.com$ [NC]  
RewriteRule (.*) https://example.com/%1/$1 [R=302,L]

There is no need for the <IfModule> wrapper here.

Test first with a 302 (temporary) redirect to avoid potential caching issues and only change to a 301 (permanent) when you are sure everything is working.

Upvotes: 1

Related Questions