how to show wildcard subdomain content based on url by .htaccess file?

If the user enters example.domain.com, I want him to see what’s in www.domain.com/example.

Another example:

User will request
example.domain.com/photos/gallery.php?from=var1&no=3,
he’ll see what’s in www.domain.com/example/photos/gallery.php?from=var&no=3.

Note: in my subfolders(wildcards) I will have WordPress installed so I have to keep in mind that URL system as well.

Answer

I assuming that you have already configured the wildcard subdomain in your DNS and your server config is configured to accept such requests. So that these subdomains all resolve to the root directory of your main domain.

I’m also assuming that you want to keep the subdomain in the browser’s address bar.

You can then do something like the following in the .htaccess file in the document root:

RewriteEngine On

RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} ^([^.]+)\.domain\.com
RewriteRule ^ /%1%{REQUEST_URI} [L]

This excludes the www subdomain from being rewritten.

Providing the subdirectory has its own .htaccess file with mod_rewrite directives (as you would expect with WordPress) then there should be nothing else you need to do.


UPDATE: However, if you don’t have WordPress installed in the subdirectory, ie. you don’t have a .htaccess containing mod_rewrite directives in the subdirectory, then you will need to modify the above code, by adding an additional condition, to prevent a rewrite loop (500 Internal Server Error).

For example:

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} ^([^.]+)\.domain\.com
RewriteRule ^ /%1%{REQUEST_URI} [L]

The condition that checks against the REDIRECT_STATUS environment variable prevents a rewrite loop by blocking rewritten requests. However, as noted above, this is unnecessary if WordPress is already installed in the subdirectory.

Attribution
Source : Link , Question Author : Mahbub Ansary , Answer Author : MrWhite

Leave a Comment