问题原文
原帖链接 · 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$1in 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.
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
