How to redirect specific URL to Subdomain

I am trying to write a .htaccess rule to redirect the URL to a subdomain.

Example: example.com/pagecategory/page-singlepagecategory.example.com/page-single

I've added wildcard subdomain on my hosting.

Can anyone help me write the .htaccess code?

Topic subdomains apache mod-rewrite url-rewriting Wordpress

Category Web


you can use a simple 301 redirect in your .htaccess file

RewriteEngine On
Redirect 301 <old_url> <new_url>

To redirect example.com/pagecategory/page-single to pagecategory.example.com/page-single, where pagecategory is entirely variable then you can do something like the following at the top of your .htaccess file:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^([a-z]+)/([\w-]+) https://$1.%{HTTP_HOST}/$2 [R,L]

I've limited the "subdomain" (ie. pagecategory) to just the lowercase characters a-z - this is saved in the $1 backreference. Likewise, $2 holds the "page-single".

Note that this is a 302 (temporary) redirect. Change R to R=301 if this is intended to be permanent, but only once you have confirmed it works as required (to avoid browser caching issues).

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.