How to prevent hotlinking of images or other assets?
Preventing images or other resources from being hot-chained can be achieved through various methods: 1. Use .htaccess to set up anti-theft chains and restrict external access by judging the Referer header; 2. Configure the valid_referers rule in Nginx to prevent illegal requests; 3. Use the Referer whitelist, signature URL and other anti-theft chain functions provided by CDN; 4. Add a watermark or provide thumbnails to the image to reduce the value of theft chain. These methods can be used alone or in combination, effectively reducing bandwidth waste.
Preventing images or other resources from being hotlinked is actually a common requirement, especially when the website traffic or bandwidth is limited. The most direct way is to restrict external sources from accessing your static resources through server configuration.
1. Set up anti-theft chain using .htaccess (for Apache)
If you are using an Apache server, you can set anti-theft link rules through the .htaccess
file. The basic idea is to judge Referer
header of the request. If it is not your own domain name, access will be denied.
Sample code:
RewriteEngine on RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{HTTP_REFERER} !^https?://(www\.)?yourdomain\.com/ [NC] RewriteRule \.(jpg|jpeg|png|gif|mp4)$ - [F,NC,L]
The meaning of this rule is: If the request source is not your own website, an external request to the image or video file will return a 403 error.
A few points to note:
- Replace
yourdomain.com
into your own actual domain name - File types can be added or decreased as needed
- If you use a CDN or allow some third-party reference resources, remember to whitelist these domain names as well
2. Use Nginx to configure anti-theft link rules
Nginx's approach is also very similar, except that the syntax is different. You can add the following content in the server or location block:
location ~ \.(jpg|jpeg|png|gif|mp4)$ { valid_referers none blocked yourdomain.com www.yourdomain.com; if ($invalid_referer) { return 403; } }
Also replace with your own domain name. After this configuration, requests from non-authorized sources will be blocked.
Tips: If you want to replace it with a prompt image instead of directly returning 403, you can use rewrite
to point to a replacement image, such as:
rewrite ^/images/(.*)$ /images/nohotlink.jpg break;
3. Use the anti-theft link function provided by CDN
Nowadays, many CDN services come with anti-theft chain functions, such as Cloudflare, Alibaba Cloud, Tencent Cloud, etc. They usually support the following ways:
- Referer Whitelist
- Signature URL (with timestamp and key)
- IP black and white list
Using a signed URL is a safer way because even if someone sees a link, it cannot be stolen at will, because the link will expire after a while.
If you are already using CDN, it is recommended to go to the console to see if there are any related settings of "anti-theft link" or "Hotlink protection". Generally, they can be enabled with one click.
4. Add watermark or thumbnail image to the image
This is not a technical anti-theft chain, but it can reduce the value of theft chain. For example, many websites first add a compressed version or watermark before displaying large images, which will not affect the user experience, but will also reduce others' willingness to copy and use them directly.
Some CMS or picture bed systems support dynamic generation of thumbnails, and can also be combined with Nginx or picture processing middleware to perform automatic cropping and watermarking operations.
Basically these are the methods. You can choose one or more combinations based on your server environment. Although the link theft cannot be completely eliminated, it can at least significantly reduce unnecessary traffic consumption.
The above is the detailed content of How to prevent hotlinking of images or other assets?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

TosetupanNginxserverblock,firstunderstanditsstructureusingtheserverdirectivewithsettingslikelisten,server_name,andlocation;next,createadirectorystructureforyoursitesuchas/var/www/example.com/htmlandsetproperpermissions;thenenabletheserverblockbycreat

To block a specific User-Agent, it can be implemented in Nginx, Apache, or code (such as PHP, Python). 1. In Nginx, judge $http_user_agent by if and return 403; 2. In Apache, use SetEnvIfNoCase and Deny to deny access; 3. judge User-Agent in the program and intercept the request. Common UAs that need to be blocked include python-requests, curl, empty UA, etc. Choosing the appropriate method can effectively reduce garbage traffic and security risks.

Key measures to protect the security of Nginx servers include: 1. Configure HTTPS encrypted connections, use Let'sEncrypt free certificates and automatically configure them through Certbot, set up forced jumps and appropriate encryption suites, and enable automatic renewal; 2. Restrict access permissions, protect sensitive paths through IP control and BasicAuth authentication; 3. Turn off information leakage, hide version numbers, prohibit directory browsing, and customize error pages to reduce the attack surface.

To efficiently provide MP4 video files, you need to enable byte range requests, optimize file structure, rational encoding and compression, and adopt strategic caching. First, enable byte range request (Accept-Ranges:bytes) to support video jumps, interrupted broadcasts and adaptive bit rate streams; second, use tools such as qt-faststart to move MOOV atoms to the beginning of the file to achieve bottom-playing; third, use H.264/H.265 encoding, reasonably set the bit rate and enable double-pass encoding to reduce the file size while ensuring quality; finally, by setting long-term Cache-Control headers and using CDN for edge caching, reduce server load and improve response speed.

Nginx failure to start is usually caused by configuration errors, port conflicts, or permission issues. First check the Nginx error log, use the command sudotail-f/var/log/nginx/error.log to view the latest error information in real time; secondly, test the configuration file syntax, run sudonginx-t to ensure there are no syntax errors; then confirm whether other processes occupy port 80 or 443, and use sudonetstat-tulpn|grep':80\|:443' to detect and handle conflicts; finally verify file permissions and ownership to ensure that Nginx has permission to access relevant directories and files.

How to implement HTTP load balancing using Nginx? The answers are as follows: 1. Use the upstream module to define the backend server group and forward the request through proxy_pass in server or location; 2. Support polling, weighted polling, minimum connection and IP hashing policies; 3. You can configure down, backup, fail_timeout and max_fails parameters to enhance stability; 4. After modifying the configuration, execute nginx-t check syntax and use nginx-sreload to take effect. For example, the basic configuration structure includes three backend nodes using polling to distribute traffic by default, while weighted polling allows the allocation of requests by weight, least_conn will send the request

When using server_name in Nginx to match multiple domains or subdomains, it can be achieved through wildcards and regular expressions. 1. When using wildcards, the asterisk can only be used for the beginning or ending, and must be a complete label boundary. For example, .example.com can match first-level subdomains but does not include root domains or multi-level subdomains. If you need to match both root domains and first-level subdomains, it should be written as example.com*.example.com; 2. When using regular expressions, you must start with ~, such as ~^\w .(dev|test)$ can match domain names ending with .dev or .test, and support capture group calls; 3. The matching priority is the exact name>Longest wildcard prefix>Longest wildcard suffix&

Set worker_processes to auto (i.e., the number of CPU cores) to make full use of multi-core performance; 2. Set worker_connections (such as 1024 or higher) according to the system file descriptor limitation and expected traffic to ensure that ulimit-n is large enough; 3. The maximum number of concurrent connections = worker_processes × worker_connections, reasonable configuration can support thousands to tens of thousands of connections, avoid bottlenecks, and improve the performance of Nginx production environment.
