Home > Software engineering >  Give 404 to desktop users using htaccess
Give 404 to desktop users using htaccess

Time:10-03

I'm looking for code that will detect if the user is on a desktop, then give them 404.

For example: If a desktop user visit example.com/loreupsum then give them 404 but not to bots; means bot can get the url contain.

and

if a mobile user visit example.com/loreupsum then show them the actual page. For this I found below code:

RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} ^.*(MSIE.*Windows\ NT|Lynx|Safari|Opera|Firefox|Konqueror) [NC]
RewriteRule ^(loreupsum)$ [L,R=404]

but this give 404 to all the users.

CodePudding user response:

This can be acheive using wp_is_mobile() that looks at the $_SERVER['HTTP_USER_AGENT'] to determine whether we're in a mobile context.

Here is a basic page template example (give_404.php) which is on the theme diretory:

<?php

/**
 * Template Name: Mobile restricted page
 *
 * @since 1.0.0
 */
if ( ! wp_is_mobile() ) {

    global $wp_query;

    $wp_query->set_404();

    status_header( 404 );

    get_template_part( 404 );

    exit();

};

get_header();

//...

get_footer();

then trigger the above template using add-action for the specfic url you want to give 404 to desktop users from fucntions.php of the theme:

add_action('wp', function() {
if ( trim(parse_url(add_query_arg(array()), PHP_URL_PATH), '/') === 'pagename' ) {
include(locate_template('give_404.php'));
exit();
}});

But how one can do it for multiple URLs. Is it possible to made a file suppose block_url.txt? That has all the url for which above template triggers.

CodePudding user response:

You could use wp_is_mobile() which is looking at the $_SERVER['HTTP_USER_AGENT'] do determine whether we're in a mobile context.

Here is a basic page template exemple:

<?php

/**
 * Template Name: Mobile restricted page
 *
 * @since 1.0.0
 */
if ( ! wp_is_mobile() ) {

    global $wp_query;

    $wp_query->set_404();

    status_header( 404 );

    get_template_part( 404 );

    exit();

};

get_header();

//...

get_footer();

But why would you do such an horrible thing !

  • Related