Search code examples
.htaccesshttp-redirectmod-rewritesubdomain

From shop.domain.com to www.domain.com (.htaccess - mod_rewrite)


I can do this with mod_rewrite?

Example 1 From Url shop.domain.com/dir/dir1/Products/skuproduct123456 to www.domain.com/products/skuproduct123456

Example 2 From Url shop.domain.com/dir/dir1/pages/namepage/123456 to www.domain.com/collections/namepage-123456

Thank You


Solution

  • What you ask sounds pretty straight forward. You just have to adapt any of the many existing examples you could have found here...

    There are two alternatives, however:

    First the usual thing is to externally redirect such requests:

    RewriteEngine on
    
    RewriteCond %{HTTP_HOST} ^shop\.example\.com$
    RewriteRule ^/?dir/dir1/Products/skuproduct123456 https://www.example.com/products/skuproduct123456 [R=301,L]
    
    RewriteCond %{HTTP_HOST} ^shop\.example\.com$
    RewriteRule ^/?dir/dir1/pages/namepage/123456 https://www.example.com/collections/namepage-123456 [R=301,L]
    

    It is a good diea to start out with a R=302 temporary redirection and only change that to a R=301 permanent redirection once everything works as expected.

    Then it could also be that you actually want to internally rewrite those requests... That is a bit more complex. If both hosts are served by the same http server things are easy again, assuming that both hosts share the same DOCUMENT_ROOT (otherwise you need to adapt the paths accordingly):

    RewriteEngine on
    
    RewriteCond %{HTTP_HOST} ^shop\.example\.com$
    RewriteRule ^/?dir/dir1/Products/skuproduct123456 /products/skuproduct123456 [END]
    
    RewriteCond %{HTTP_HOST} ^shop\.example\.com$
    RewriteRule ^/?dir/dir1/pages/namepage/123456 /collections/namepage-123456 [END]
    

    If however both hosts are served by separate http servers, the only option you have is to use the proxy module. That is also possible from within the rewriting module. This comes with a massive performance penalty though because of how network routing is setup in that case...

    All approaches can be implemented not only for static, literal paths you implement but also in a more generic way using regular expressions as patterns. The exact rule depends on the actual structure of your URLs in that case, which you did not really name.


    In general it is a good idea to implement such rules in the actual http server's host configuration. You can also use a distributed configuration file (often named ".htaccess"), but that comes with disadvantages. It is only offered as a last means for situations where you do not have control over the http server configuration (read: cheap web hosting providers).