Home > Back-end >  How can I redirect subdomain.domain.com/* to domain.com/folder/*
How can I redirect subdomain.domain.com/* to domain.com/folder/*

Time:02-03

I have to make a redirection on a .htaccess file.

I want to access the content of a folder from a subdomain url like this:

subdomain.domain.com/* => domain.com/folder/*

The folder contains pdf files and I want to acces it with this url for example:

subdomain.domain.com/file.pdf

I'm new into htaccess redirection rules and I'm a little lost.

I tried something like this and test it into https://htaccess.madewithlove.com/

RewriteCond %{HTTP_HOST} ^subdomain.domain.com/*$
RewriteRule ^(.*) https://domain/folder/ [L,R=301]

This code works on the tester but on my website it throws me the error : "The connection was reset".

Do you have any idea on it?

UPDATE

Following some advices I try but it doesn't work

RewriteCond %{HTTP_HOST} ^subdomain\.example\.com/
RewriteRule (. \.pdf)$ https://example.com/folder/$1 [R=302,L]

CodePudding user response:

RewriteCond %{HTTP_HOST} ^subdomain.domain.com/*$
RewriteRule ^(.*) https://domain/folder/ [L,R=301]

You are not doing anything with the captured URL-path (ie. (.*)) so this will always redirect to https://domain/folder/ (no file).

I would also question whether this should be a 301 (permanent) redirect. Maybe a 302 (temporary) redirect would be preferable here? Note that the 301 is cached, so you will need to clear your browser cache before testing.

It should be like this:

RewriteCond %{HTTP_HOST} ^subdomain\.domain\.com
RewriteRule (.*) https://domain/folder/$1 [R=302,L]

The $1 backreference contains the URL-path captured in the RewriteRule pattern.

The Host header (ie. the value of the HTTP_HOST server variable) contains the hostname only. There is no URL-path component. (Fortunately /* matches the slash 0 or more times, so it still "worked" in your testing.)

However, if the folder only contains .pdf files then you should be more restrictive and redirect only .pdf requests. For example:

:
RewriteRule (. \.pdf)$ https://domain/folder/$1 [R=302,L]
  • Related