如何将文件重定向至自定义CDN脚本?附具体示例需求
Hey there! Let's walk through how to set up that exact redirect for your custom CDN script. Below are solutions for the two most common web servers—pick the one that matches your setup:
If you're running Apache, edit or create a .htaccess file in the root directory of your example.com site, then add these lines:
RewriteEngine On # Ensure the rule only applies to requests for your main domain (case-insensitive) RewriteCond %{HTTP_HOST} ^example\.com$ [NC] # Redirect all contents/... paths to your CDN script with the captured path as a parameter RewriteRule ^contents/(.*)$ http://cdn.example.com/cdn.php?url=contents/$1 [L,R=302]
Quick rule breakdown:
RewriteEngine On: Enables Apache's URL rewriting functionality.[NC]: Makes the domain match case-insensitive (soExample.comworks too).(.*): Captures everything aftercontents/into the$1variable, which we pass to the CDN script'surlparameter.[L,R=302]:[L]tells Apache this is the final rule for the request;R=302sets a temporary redirect. Swap this toR=301if you want a permanent redirect (better for long-term SEO).
For Nginx, edit your server block config for example.com (usually stored in /etc/nginx/sites-available/ or similar), then add this location block inside the server block:
server { listen 80; server_name example.com; # Your existing site config (root, index files, etc.) goes here... # Redirect contents paths to the CDN script location ~ ^/contents/(.*)$ { return 302 http://cdn.example.com/cdn.php?url=contents/$1; } }
Nginx-specific notes:
- Replace
302with301for a permanent redirect. - If you use HTTPS, update the redirect URL to
https://and ensure your SSL config is set up correctly. - After making changes, reload Nginx to apply them:
sudo systemctl reload nginx
Quick verification tip
To check if the redirect works as expected, run this curl command in your terminal:
curl -I http://example.com/contents/2018/01/image.png
You should see a Location header pointing directly to your CDN script with the correct url parameter.
内容的提问来源于stack exchange,提问作者fabianpnke

