【问题标题】:Rewrite subdomain to main domain for images only using htaccess仅使用 htaccess 将图像的子域重写为主域
【发布时间】:2013-12-19 09:29:19
【问题描述】:

我有一个域,其中除 image\css 等之外的所有内容都由单个 php 文件处理。然而,在重组后,许多图像已从子域移至主域。因此,我正在寻找一种方法将所有 image\css 文件重定向到主域,如果它们最初位于其中一个子域上。我当前的代码是

RewriteEngine On
RewriteCond %{REQUEST_URI}  !(\.png|\.jpg|\.gif|\.jpeg|\.ico|\.bmp|\.css|\.ts|\.js)$
RewriteRule !^index\.php$ /index.php [L]

我尝试了几种方法来重定向它,但无论我尝试什么,我似乎都违反了现有规则。

谢谢

我想出的最终解决方案

RewriteEngine On
# Check the request isn't for the main domain
RewriteCond %{HTTP_HOST} !^domain\.com$
# Check the request is for a static resource
RewriteCond %{REQUEST_URI} \.(png|jpg|gif|jpeg|ico|bmp|css|ts|js)$
# Redirect to main domain
RewriteRule (.*) http://domain\.com/$1 [R=301,L]
# if the request isn't for index.php,
# (invisibly) redirect to index.php
RewriteCond %{REQUEST_URI}  !(\.png|\.jpg|\.gif|\.jpeg|\.ico|\.bmp|\.css|\.ts|\.js)$
RewriteRule !^index\.php$ /index.php [L]

仅供参考。真的要感谢 jon 的答案,我只是根据自己的需要对其进行了调整。

【问题讨论】:

    标签: image .htaccess redirect subdomain


    【解决方案1】:

    如果您的 HTML 中的 URL 仍指向子域,则您需要在这些子域上设置 htaccess 重定向,而不是在主域上,因为请求仍将转到子域。

    例如在/var/www/vhosts/sub.domain.com/httpdocs/.htaccess:

    RewriteEngine On
    RewriteCond %{REQUEST_URI} \.(png|jpg|gif|jpeg|ico|bmp|css|ts|js)$
    RewriteRule (.*) http://domain.com/$1 [R=301,L]
    


    /var/www/vhosts/sub2.domain.com/httpdocs/.htaccess:

    RewriteEngine On
    RewriteCond %{REQUEST_URI} \.(png|jpg|gif|jpeg|ico|bmp|css|ts|js)$
    RewriteRule (.*) http://domain.com/$1 [R=301,L]
    

    更新

    根据您的评论,即 Apache 将每个子域视为主域,请尝试以下操作:

    RewriteEngine On
    # Check the request isn't for the main domain
    RewriteCond %{HTTP_HOST} !(www\.)?domain\.com$
    # Check the request is for a static resource
    RewriteCond %{REQUEST_URI} \.(png|jpg|gif|jpeg|ico|bmp|css|ts|js)$
    # Redirect to main domain
    RewriteRule (.*) http://domain.com/$1 [R=301,L]
    

    【讨论】:

    • 谢谢,这会奏效,但我错过了一个关键细节(对不起,我的错)我已经设置了 apache,以便它处理所有子域,就好像它们是主域一样。所以在短期内图像仍然有效,但从长远来看,我想重定向它们,以便搜索引擎等停止寻找子域。
    • 刚刚完成检查,图像未正确重定向。我已经用正确的域替换了对 domain.com 的两个引用,然后将其粘贴到我现有代码的上方。 (这样页面仍然重定向到 index.php),我还在第一个 domain.com 中留下了 \,不确定它是否是正则表达式的一部分。只是为了澄清我想要 jon.blog.com\fred\test.jpg 重定向到 blog.com\fred\test.jpg
    • 认为我已经排序了,我不使用 www,我只使用域\子域。我对此进行了一些调整,最终得到了我添加到问题中的代码,但我会将你的答案标记为已接受因为没有你的答案我不会到达那里,我只调整了大约 5 个字符: -)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    • 2012-01-25
    • 1970-01-01
    相关资源
    最近更新 更多