Make images private in Wordpress Make images private in Wordpress wordpress wordpress

Make images private in Wordpress


You can make this as complicated or as simple as you want. The simplest is to check the referrer as suggested by Hemnath Mouli but that can spoofed easily.

However, if you want to go really deep... ;)

Use .htacess file with a RewriteRule to rewrite all images into a PHP script that bootstraps Wordpress and checks the user's authentication status. Also you should add an .htaccess file to your images folder to deny direct access to the folder to exclude edge cases.

WARNING: THIS CODE IS JUST PROOF OF CONCEPT TO GET YOU STARTED!!

.htaccess

RewriteRule ^(.*\.(jpg|gif|png))$ isAuthenticated.php?path=$1

isAuthenticated.php

require_once("wp-blog-header.php");$allowedExtensions = array("jpg", "gif", "png");$path = $_SERVER["DOCUMENT_ROOT"].DIRECTORY_SEPARATOR.$_REQUEST["path"];$pathInfo = pathinfo($path);// Check if the Wordpress user is logged in and if the file extension is allowed// @see https://codex.wordpress.org/Function_Reference/is_user_logged_inif (!is_user_logged_in() || !in_array($pathInfo["extension"], $allowedExtensions)) {    header("HTTP/1.1 403 Forbidden");    exit;}if(!file_exists($path)) {    header("HTTP/1.1 404 Not Found");    exit;}// Display the file and set the correct mimetype$resource = finfo_open(FILEINFO_MIME_TYPE);$mimetype = finfo_file($resource, $path);finfo_close($resource);header("Content-Type: ".$mimetype);readfile($path);


Use .htaccess

RewriteEngine on RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost [NC] RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost.*$ [NC] RewriteRule \.(gif|jpg)$ - [F]

Returns 403 if you access image directly, but allows them to be displayed on site.


Use .htaccess

RewriteEngine on RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost [NC] RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost.*$ [NC] RewriteRule \.(gif|jpg)$ - [F]