Reputation:
I have two version of my site. one is a mobile version and another one is desktop.
Path looks like this :
For Mobile : public_htm/mobile
For Desktop : public_html
I want to change the document root of my domain based on the device. I want to serve content from the mobile
folder if the user's device is mobile & serve contents from public_html if user on desktop.
How can I do this with .htaccess
?
I want to have my domain the same for both desktop and mobile, only document root changed by .htaccess
based on the device.
Upvotes: 1
Views: 892
Reputation: 45978
You would need to add something like the following to the top of the root .htaccess
file:
RewriteEngine On
# Prevent direct access to the "/mobile" subdirectory
# - redirect back to the root
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^mobile/(.*) /$1 [R=301,L]
# Rewrite all requests from mobile devices to the "/mobile" site
RewriteCond %{HTTP_USER_AGENT} ^iphone|android|etc$ [NC]
RewriteRule ^(?!mobile/).* mobile/$0 [L]
The mobile detection regex (RewriteCond
directive) is just an example, the specifics are left up to the reader. (For reference: mobile browser user-agent strings)
The negative lookahead in the RewriteRule
pattern prevents requests that have already been rewritten to the /mobile
subdirectory from being repeatedly rewritten. If you have another .htaccess
in the /mobile
subdirectory containing mod-rewrite directives then this may be unnecessary.
The first rule redirects any direct traffic to the /mobile
subdirectory back to the document root. However, if you have another .htaccess
file in the /mobile
subdirectory containing mod-rewrite directives then this redirect would need to be moved to that .htaccess
file (it won't work here).
Just a note on terminology... This doesn't strictly change the "document root", as mentioned in the question. (Although it might "look like" it does from a client perspective.) This internally rewrites requests to a subdirectory (URL-rewriting). Server-side applications running in the /mobile
subdirectory still see the document root as being the parent directory. You cannot change the "document root" in .htaccess
, which can only be done by setting the DocumentRoot
(or VirtualDocumentRoot
) directive(s) in the server config.
Upvotes: 1