首页 > 解决方案 > How can I Redirect subdomain with path to root domain without this path

问题描述

I need help with this case

I need to redirect (301) a subdomain test.example.com/?preview_theme=niss-promag to https://example.com without /?preview_theme=niss-promag

I already used code but it's redirecting to root domain with the same path https://example.com/?preview_theme=niss-promag

This is the code currently used:

RewriteEngine on 
RewriteCond %{HTTP_HOST} ^test.example.com$
RewriteRule ^(.*)$ https://example.com [L,R=301]

Note: I need to redirect whatever path of the subdomain to root domain I don't specify the one above!

标签: .htaccessredirectmod-rewriteurl-rewritingsubdomain

解决方案


This should be working:

RewriteEngine on 
RewriteCond %{HTTP_HOST} ^test\.example\.com$
RewriteCond %{QUERY_STRING} ^preview_theme=niss-promag$
RewriteRule ^(.*)$ https://example.com [QSD,R=301]

It is a good idea to start out with a 302 temporary redirection and only change that to a 301 permanent redirection later, once you are certain everything is correctly set up. That prevents caching issues while trying things out...

If that does not work then most likely your http server is outdated, try something like that:

RewriteEngine on 
RewriteCond %{HTTP_HOST} ^test\.example\.com$
RewriteCond %{QUERY_STRING} ^preview_theme=niss-promag$
RewriteRule ^(.*)$ https://example.com/? [R=301]

This implementation will work likewise in the http servers host configuration or inside a dynamic configuration file (".htaccess" file). Obviously the rewriting module needs to be loaded inside the http server and enabled in the http host. In case you use a dynamic configuration file you need to take care that it's interpretation is enabled at all in the host configuration and that it is located in the host's DOCUMENT_ROOT folder.

And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using dynamic configuration files (".htaccess"). Those dynamic configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).


推荐阅读