You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将文件重定向至自定义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:

Apache (Using .htaccess)

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 (so Example.com works too).
  • (.*): Captures everything after contents/ into the $1 variable, which we pass to the CDN script's url parameter.
  • [L,R=302]: [L] tells Apache this is the final rule for the request; R=302 sets a temporary redirect. Swap this to R=301 if you want a permanent redirect (better for long-term SEO).
Nginx (Server Block Configuration)

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 302 with 301 for 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:31:43