Home » Php » Where should I put the Mobile detection in .htaccess or php?

Where should I put the Mobile detection in .htaccess or php?

Posted by: admin July 12, 2020 Leave a comment


I have a mobile version of my site working now and I want to know where should I do the redirection. I only can think to do redirection using:

  • .htaccess
  • PHP

I would like to know which one is better/more efficient? Is there a better way to do that other than in the .htaccess or PHP?


How to&Answers:

I vote for Apache.

If you do it at the Apache level (in the .htaccess file or, even better, in the Apache config), then if you have HTML files, the only way to detect this that I can think of is JavaScript; this can be easily removed (like disabling JavaScript).

This also applies to other types of files, like PDFs, Word documents, MP3 files, etc. It can easily redirect to a page that contains a “not available for mobile” message.

The other thing I can think of is a css file if they are different (standard version vs mobile version).


Definitely PHP. You should allow clients to switch from mobile version to full version and back, so there will be some cookies involved.

It is good practice to run full version on www.example.com and mobile version on different subdomain, m.example.com


By doing it in PHP, you can make some automatic adjustments to refine the same content for mobile viewers, without necessarily having to have completely different copies of your content. This article on mobile-friendly PHP design gives some details. You probably do not want to follow all the tips it gives, since it’s from the days when mobile data speeds meant minimal images were best, BUT it can give you ideas on methods you can use to make adjustments.

Basically, it amounts to creating a function to adjust the HTML output in whatever ways make the most sense for your site. Then you put that function into a single file that is included on every page via .htaccesss (so I guess you’re kind of doing both PHP and .htaccess). And part of that inclusion is to use ob_start(); to run the function on the page’s output on load.