Search code examples
.htaccess

Open a website only on mobile site if it is opened from the desktop redirects to another page with .htaccess


I have a problem. I need my website to only be entered from mobile devices, and if they enter from a desktop site that redirects it to another page, what I achieve is this,

RewriteCond %{QUERY_STRING} !^android
RewriteCond %{HTTP_USER_AGENT} "Windows" [NC]
RewriteRule ^$ https://google.com [L,R=302]

it works fine, but if you enter another subdirectory like mywebsite.com/cats can be entered from the desktop, how can I block the subdirectories and redirect it to another website


Solution

  • Your RewriteRule only matches the empty path, so a URL like https://example.com/. You however want to match any path, so that all requests get redirected. So you simply need to change your matching pattern:

    RewriteCond %{QUERY_STRING} !^android [NC]
    RewriteRule ^ https://example.com/ [L,R=302]
    

    An alternative would be to preserve the requested path for the redirection target (depends on what you actually want to achieve):

    RewriteCond %{QUERY_STRING} !^android [NC]
    RewriteRule ^ https://example.com%{REQUEST_URI} [L,R=302]
    

    You are currently using a R=302 temporary redirection. Great for testing thigns! But keep in mind to change that to a R=301 permanent redirection once everything works as expected.

    I also removed that second condition from your rule. Not all "desktop systems" use a MS-Windows operating systems. There are many MacOS and Linux based systems you also want to handle, I assume.