Mobile website redirection based on user agent

2019-08-20 08:18发布

问题:

Say I've got two distinct domains:

 1) http://sub.test.org
 2) http://m.sub.test.org

for my website.

I want domain n.1 to be associated to the full-version of my website (intended to be mainly visited by desktop user agents) and domain n.2 to be associated to its mobile-version (intended to be mainly visited by mobile user agents).

Both of the versions reside on an external host which runs an instance of Apache webserver I can't control directly, but I am able to post .htaccess files and therefore I want them to control domain redirecting stuff (I don't want to use Javascript neither PHP server-side logic)

The directory structure on the external host is, say:

directory / --> contains full-version website's pages and resources 
                (index.html is the entry-point)

directory /mobile --> contains full-version website's pages and resources 
                      (index.html is the entry-point)

and the mappings are:

http://sub.test.org -> /index.html
http://m.sub.test.org -> /mobile/index.html

Now, my desired scenarios are as follows:

A) When user asks for URL http://sub.test.org:

  1. IF current URL is http://m.sub.test.org/* (this means: if user is currently into the mobile-version) THEN serve page http://sub.test.org/index.html
  2. ELSE:
    1. IF user agent is mobile THEN redirect to URL http://m.sub.test.org
    2. ELSE serve page http://sub.test.org/index.html

B) When user asks for URL http://m.sub.test.org - no matter what the user agent is - user should be redirected to URL http://sub.test.org.

My questions:

  • What would be the syintax of the associated .htaccess file?
  • Do I need more than one?
  • Where should I place it/them ?

Any help/code hint would be really appreciated, because I have really a few experience with Apache .htaccess files and regexps! Thanks in advance.

回答1:

  • http://httpd.apache.org/docs/current/howto/htaccess.html
  • You would most likely need 2
  • place one it in the root and one in /mobile