大网数据广告活动
网站运营与故障问答

301 redirect with regex: how to match any file at top domain level (not in a subdirectory)?

· 52CE 我爱测

I need to redirect URLs of all .dmg files at domain's top level to specific folder. By way of example: http://example.com/file.dmg to http://example.com/downloads/file.dmg I can't hard code the domain name because it's a temporar…

问题原文

原帖链接 · Leo Braun · CC BY-SA 4.0

I need to redirect URLs of all .dmg files at domain's top level to specific folder.

By way of example:

http://example.com/file.dmg to http://example.com/downloads/file.dmg

I can't hard code the domain name because it's a temporary domain which will be switched once the new website is completed.

I don't understand why the following doesn't work:

RewriteRule ^.*\.com/(.*)\.dmg$ /downloads/$1.dmg [R=301,L,NC] 

I get "page not found" error. A .htaccess tester website also reports failure.

What am I missing?

It's a WordPress website if it makes any difference.

已采纳解答

原帖链接 · Stephen Ostermiller · CC BY-SA 4.0

A RewriteRule only matches the file path. You can't include part of the domain name in the rewrite rule because the rule will never match it.

To match something at the start of the path, use the "starts with" regex operator: ^.

To ensure that you are not matching anything in sub-directories, make sure not to match any slashes in your pattern. [^/]+ instead of .* means "at least one character that isn't a slash" rather than "zero or more characters". The caret inside the square bracket is the negation of a character set.

Your final rewrite rule should be:

RewriteRule ^/?([^/]+\.dmg)$ /downloads/$1 [R=301,L,NC]
  • ^/?: starts with an optional slash
  • (...): parenthesis around the file name (including ".dmg") which becomes $1 in the replacement
  • [^/]+: At least one character other than slashes
  • \.: A literal period
  • $: "ends with", ensure there is nothing after the file name

Make sure this rewrite rule is at the top of your .htaccess file so that it takes precedence over other rewrite rules including the default wordpress rules.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Webmasters Stack Exchange
适用范围
以原帖系统、软件版本与发布日期为准(2020-08-05)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。