首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >强制某些文件重定向(基于引用),否则触发404页

强制某些文件重定向(基于引用),否则触发404页
EN

Stack Overflow用户
提问于 2013-04-22 15:17:30
回答 2查看 642关注 0票数 1

我们通过一个下载链接分发不同版本的软件产品。传递是基于referer与默认值一起进行的,该默认值运行良好。此外,如果使用了错误的文件名,则应该将用户重定向到404-page。

目前,.htaccess-file看起来如下:

代码语言:javascript
复制
# stop directory listing
Options -Indexes

# turn rewrite engine on
RewriteEngine On

# force 404 if file name is missing or wrong
RewriteCond %{REQUEST_URI} !^(download_mac\.zip|download_pc\.zip)$
RewriteRule (.*) 404/index.html [L]

# an example based on the referer
RewriteCond %{HTTP_REFERER} ^http://([^.]+\.)*domain-a\.com [OR]
RewriteCond %{HTTP_REFERER} ^http://([^.]+\.)*domain-b\.com
RewriteRule ^(download_mac\.zip|download_pc\.zip)$ domain_ab/$1 [L]

# last rule if no referer matches
RewriteRule ^(download_mac\.zip|download_pc\.zip)$ default/$1 [L]

因此,我对这个文件有一个问题和一个额外的问题:

  1. 第一条规则,强制404,是非常贪婪的,每次都会得到错误页面,不管调用什么URL。我也尝试过像RewriteCond %{REQUEST_URI} !^download_mac\.zip$这样的单一语句,但没有任何效果。我怎么才能解决这个问题?
  2. 我如何处理其他规则中的文件名?我尝试过像RewriteRule ^(.*)$ default/$1 [L]这样的东西,但是它给了我一个困难的时间和一个500 Internal Server Error
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-04-22 16:07:59

通过使用这样的Env变量,可以避免重复文件名:

代码语言:javascript
复制
RewriteRule ^(download_mac\.zip|download_pc\.zip)$ - [E=ALLOWED:$1,NC]

RewriteCond %{ENV:ALLOWED} ^$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /404/index.html [L]

RewriteCond %{ENV:ALLOWED} !^$
RewriteCond %{HTTP_REFERER} ^http://([^.]+\.)*domain-a\.com [OR]
RewriteCond %{HTTP_REFERER} ^http://([^.]+\.)*domain-b\.com
RewriteRule ^ /domain_ab/%{ENV:ALLOWED} [L]

RewriteCond %{ENV:ALLOWED} !^$
RewriteRule ^ /default/%{ENV:ALLOWED} [L]
票数 1
EN

Stack Overflow用户

发布于 2013-04-22 16:33:37

你可以把重写规则移到最后。其他规则处理有效案例,如果它们都不匹配,则应用最后一条规则。

代码语言:javascript
复制
# an example based on the referer
RewriteCond %{HTTP_REFERER} ^http://([^.]+\.)*domain-[ab]\.com
RewriteRule ^download_(mac|pc)\.zip$ domain_ab/$0 [L]

# last rule if no referer matches
RewriteRule ^download_(mac|pc)\.zip$ default/$0 [L]

# force 404 if file name is missing or wrong
RewriteRule ^ 404/index.html [L]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16150647

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档