301 redirect with regex: how to match any file at top domain level (not in a subdirectory)?
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.
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.
Comments
Post a Comment