Pankaj Agrawal
Pankaj Agrawal

Reputation: 203

Redirect Subdomain to domain while preserving the path and query string

I have a subdomain and I want to redirect to the main domain (using .htaccess) like so:

  1. https://abc.example.com I want to redirect it to https://www.example.com
  2. https://abc.example.com/path/page-name to https://www.example.com/path/page-name
  3. https://abc.example.com/path/page-name?test=12&test1=12 to https://www.example.com/path/page-name?test=12&test1=12

Please suggest how I can do it.

I have already tried the below solution but its not working.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^(.+)\.example\.com$   [NC]
RewriteRule ^ http://www.example.com/suberror  [L,R]

I am using Laravel.

Upvotes: 0

Views: 303

Answers (2)

DocRoot
DocRoot

Reputation: 1201

Assumptions:

  • You have 1 subdomain (as stated in your example)
  • The subdomain and main domain point to the same area on the filesystem (they share a common root).

The try something like the following at the top of your .htaccess file:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^abc\.example\.com [NC]
RewriteRule ^ http://www.example.com%{REQUEST_URI}  [R,L]

The URL-path from the request is held in the REQUEST_URI server variable. The query string from the request is passed through to the substitution (target) without any additional work.

Upvotes: 1

Mohammed Elhag
Mohammed Elhag

Reputation: 4302

At this line :

RewriteRule ^ http://www.example.com/suberror  [L,R]

There is no pattern means , regex checked against requested URI .

Change it to this :

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

This part ^(.*)$ is pattern and it will be presented in substitution by this $1

If it is Ok , Change [L,R] to [L,R=301] to be permanent redirection because R alone means R=302 which is temporary .

Upvotes: 1

Related Questions