Search code examples
apache.htaccesshttp-redirectmod-rewritehttp-status-code-301

.htaccess redirect to subdomain url with hash


I'm trying to redirect a site with the following url structure:

https://example.com/2021/about to https://2021.example.com/#about

https://example.com/2021/visit to https://2021.example.com/#visit

how can i do this?

i tried adding this to the /about directory in the original domain:

RewriteEngine on
RewriteBase /
RewriteRule (.*)  https://2021.example.com/#about [R=301,NE, L]

but what i got after the redirect was https://2021.example.com/#about2021/about

which is not right. any help is appreciated

[EDIT] i only want to apply this to some folders, like /2021/about and 2021/visit


Solution

  • You may use this redirect rule:

    RewriteEngine On
    
    RewriteCond %{HTTP_HOST} ^(?:www\.)?(example\.com) [NC]
    RewriteRule ^(20\d{2})/(.+?)/?$ https://$1.%1/#$2 [R=301,L,NE]
    

    Make sure this is your topmost rule in .htaccess and you clear your browser cache before testing this new rule.